Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 81

CSC 308: Java Programming

Data Structures &


Generic Programming
Denis L. Nkweteyim
Outline

Data Structures

Self-referential classes (Lists, Stacks and
Queues)

Generic Programming

Collections

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 2

Self-referential Classes

Self-referential class

Contains an instance of a class that refers to
another object of the same class type

Basis of linked lists, and stacks, queues, trees, etc.
Illustration

class Node {
private int data;
private Node nextNode; //reference to next linked node public Node(int data)
{ /*constructor body*/ } public int getData() { /*method body */ }
public void setData(int data) {/*method body */ } public Node getNextNode()
{/*method body */ } public void setNextNode(Node nextNode) {/*method body */ } }
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 3

Self-referential Classes: Linked


Lists package list;
// class to represent one node in a list
class ListNode {
Object data;
ListNode nextNode;
ListNode(Object object) {
this(object, null);
}
ListNode(Object object, ListNode node){
data = object;
nextNode = node;
}
Object getObject() {
return data;
}
ListNode getNextNode() {
return nextNode;
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 4

Self-referential Classes: Linked Lists


// class List definition
public class List {
private ListNode firstNode, ListNode lastNode;
private String name;
public List() {
this("list");
}
public List(String listName) {
name = listName; firstNode = lastNode = null; }
public void insertAtFront(Object insertItem) {
if (isEmpty()) firstNode=lastNode = new ListNode(insertItem); else
firstNode = new ListNode(insertItem, firstNode); }
public void insertAtBack(Object insertItem) {
if (isEmpty())
firstNode = lastNode = new ListNode(insertItem); else
lastNode=lastNode.nextNode=new ListNode(insertItem);
} May 25, 2022 D. L. Nkweteyim - CSC 308 (Java
Programming - DS & Generics) 5

Self-referential Classes: Linked Lists


public Object removeFromFront() throws EmptyListException { if (isEmpty())
throw new EmptyListException(name); Object removedItem = firstNode.data;
// update references firstNode and lastNode
if (firstNode == lastNode) firstNode = lastNode = null; else firstNode =
firstNode.nextNode;
return removedItem;
}
public Object removeFromBack() throws EmptyListException { if (isEmpty())
throw new EmptyListException(name); Object removedItem = lastNode.data;
// update references firstNode and lastNode
if (firstNode == lastNode)
firstNode = lastNode = null;
else {
ListNode current = firstNode;
while (current.nextNode != lastNode)
current = current.nextNode;
lastNode = current;
current.nextNode = null;
}
return removedItem;
} May 25, 2022 D. L. Nkweteyim - CSC 308 (Java
Programming - DS & Generics) 6

Self-referential Classes: Linked Lists


// determine whether list is empty
public boolean isEmpty() {
return firstNode == null;
}
public void print(){
if (isEmpty()) {
System.out.printf("Empty %s\n", name); return;
}
System.out.printf("The %s is: ", name); ListNode current =
firstNode;
while (current != null) {
System.out.printf("%s ", current.data); current =
current.nextNode;
}
System.out.println("\n");
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 7

Self-referential Classes: Linked Lists


package list;
public class EmptyListException extends RuntimeException { public
EmptyListException() {
this("List"); //call the 1-argument constructor }
public EmptyListException(String name){
super(name + " is empty"); //call superclass constructor }
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 8

Self-referential Classes: Linked Lists

package list;
public class ListTest {
public static void main(String[] args) {
List list = new List(); // create the List container // insert integers in list
list.insertAtFront(-1);
list.print();
list.insertAtFront(0);
list.print();
list.insertAtBack(1);
list.print();
list.insertAtBack(5);
list.print();

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 9

Self-referential Classes: Linked Lists


// remove objects from list; print after each removal try {
Object removedObject = list.removeFromFront(); System.out.printf("%s
removed\n", removedObject); list.print();
removedObject = list.removeFromFront(); System.out.printf("%s removed\
n", removedObject); list.print();
removedObject = list.removeFromBack();
System.out.printf("%s removed\n", removedObject); list.print();
removedObject = list.removeFromBack();
System.out.printf("%s removed\n", removedObject); list.print();
} // end try
catch (EmptyListException emptyListException) { System.out.printf("%s\n%s\n",
"Exception handler code goes here",emptyListException);
} // end catch
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 10

Self-referential Classes: Linked Lists


The list is: -1

The list is: 0 -1


The list is: 0 -1 1

The list is: 0 -1 1 5

0 removed
The list is: -1 1 5

-1 removed
The list is: 1 5

5 removed
The list is: 1

1 removed
Empty list
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 11

Self-referential Classes: Stacks



We can create a stack from a linked list
by extending the linked list

…and calling only the methods that are
relevant to stacks

We can also use composition instead of
inheritance

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 12

Self-referential Classes:
Stacks (Inheriting from
Linked List)
package list;
public class StackInheritance extends List { public
StackInheritance() {
super("stack");
}
// add object to stack
public void push(Object object)
{
insertAtFront(object);
} // end method push
// remove object from stack
public Object pop() throws EmptyListException { return
removeFromFront();
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 13

Self-referential Classes: Stacks


(Inheriting from Linked List)
package list;
public class StackInheritanceTest {
public static void main(String args[]) {
StackInheritance stack = new StackInheritance(); stack.push(-1); stack.print();
stack.push(0); stack.print();
stack.push(1); stack.print();
stack.push(5); stack.print();
try {
Object removedObject = null;
while (true) {
removedObject = stack.pop();
System.out.printf("%s popped\n", removedObject); stack.print();
}
}
catch (EmptyListException emptyListException) { }
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 14
Self-referential Classes: Stacks
(Inheriting from Linked List)
The stack is: -1

The stack is: 0 -1

The stack is: 1 0 -1

The stack is: 5 1 0 -1

5 popped
The stack is: 1 0 -1

1 popped
The stack is: 0 -1

0 popped
The stack is: -1

-1 popped
Empty stack
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 15

Self-referential Classes: Stacks (Using


Composition)
public class StackComposition {
private List stackList;
public StackComposition() {
stackList = new List( "stack" );
}
// add object to stack
public void push(Object object) {
stackList.insertAtFront( object );
}
// remove object from stack
public Object pop() throws EmptyListException { return stackList.removeFromFront(); }
// determine if stack is empty
public boolean isEmpty() {
return stackList.isEmpty();
}
// output stack contents
public void print() {
stackList.print();
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 16 }
Self-referential Classes:
Queues Example
package list;
public class Queue {
private List queueList;
public Queue(){
queueList = new List("Queue");
}
public void enqueue(Object object){
queueList.insertAtBack(object);
}
public Object dequeue() throws EmptyListException { return
queueList.removeFromFront(); }
public boolean isEmpty(){
return queueList.isEmpty();
}
public void print(){
queueList.print();
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 17

Outline

Data Structures

Type Wrapper Classes ●

Generic Programming ●

Collections
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 18

Generic Methods and Classes



Motivation

How to create general models to do things

Generics

Enable programmers to specify, with a single method declaration, a
set of related methods

Enables programmers to specify, with a single class declaration, a
set of related types

Examples

A single sort method to sort elements in Integer arrays, String
arrays, or arrays of any type that supports sorting

A single Stack class that supports integers, floating point
numbers, etc.
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 19


Consider this overloaded methods program public static void printArray(Integer[] inputArray) { for (Integer
element : inputArray)

We could have used arrays of primitive types System.out.printf("%s ", element);
System.out.println();
But only reference types can be used with generic

}
methods and classes public static void printArray(Double[] inputArray) { for (Double

…so we use corresponding wrapper class types element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
public static void printArray(Character[] inputArray) { for (Character
element : inputArray)
System.out.printf("%s ", element);
Array integerArray contains: 1 2 3 4 5 6 System.out.println();
}
public static void main(String args[]) {
Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7
Integer[] integerArray = {1,2,3,4,5,6};
Double[] doubleArray = {1.1,2.2,3.3,4.4,5.5,6.6,7.7}; Character[]
Array characterArray contains: H E L L O characterArray = {'H','E','L','L','O'}; System.out.println("Array

Generic Methods
integerArray contains:"); printArray(integerArray); // pass an Integer
array System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array System.out.println("\
nArray characterArray contains:"); printArray(characterArray); // pass
a Character array }
package generics; }
public class OverloadedMethods {
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 20

Generic Methods

Program notes

printArray methods

Array element type appears in two locations in each
method: Method header, and the for statement

By replacing element types in each method with a
generic name, the three overloaded methods can
be compacted into:

public static void printArray(E[] inputArray) { for (E element :


inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 21

Generic Methods

Reimplementation of program using generics
package generics;
public class GenericMethodTest {
public static <E> void printArray(E[] inputArray) { for (E element :
inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
Integer[] intArray = {1, 2, 3, 4, 5};
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7}; Character[] charArray = {'H',
'E', 'L', 'L', 'O'}; System.out.println("Array integerArray contains:");
printArray(intArray); // pass an Integer array System.out.println("\nArray doubleArray
contains:"); printArray(doubleArray); // pass a Double array System.out.println("\
nArray characterArray contains:"); printArray(charArray); // pass a Character array }
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 22
Generic Methods

Program notes

Generic method declarations have a type parameter section
delimited by angle brackets < > that precedes the method
return type

public static <E> void printArray(E[] inputArray) Type parameters

receive actual type arguments when the method is called



Type parameters can represent only reference types, not primitive
types

Type Erasure
When compiler translates a generic method, it removes the type

parameter section and replaces type parameters with actual types ●

This process is called type erasure



When instantiated, the above translates to the following method
public static void printArray(Object[] inputArray)

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 23
Generic Methods

Upper Bounds of Type Parameters

In the process of erasure, type parameters are
replaced with their upper bound
Unless specified otherwise, Object is the

default upper bound for type parameters



To explicitly declare an upper bound on a type
parameter, use the keyword extends, followed
by the class or interface that is to be the upper
bound.
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 24

Upper Bounds of Type


Parameters Example: the
compareTo method

The compareTo method is used to compare two objects of
the same class (i.e., determine which one is larger) if that
class implements the generic interface Comparable<T>
If a generic method will use the compareTo method, we must

declare the Comparable<T> generic interface as the upper


bound as in this example

public static <T extends Comparable<T> > T
minimum(T x,T y,T z) Return type parameters

public static <T extends Comparable<T> > T minimum(T x,T y,T z)

method name
Comparable interface type parameter

Note: All Comparable<T > objects have a compareTo() method

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 25

Upper Bounds of Type


Parameters Example: the
compareTo method

The translated version of the method after
erasure will be:

public static Comparable
minimum(Comparable x, Comparable y,
Comparable z)

Now, the following call is legal, since String
implements Comparable< String>

String min = minimum("one", "three","eight");

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 26

Generic Methods: Minimum of three


objects
package generics;
public class MinimumTest {
//determines the min of three Comparable objects
public static <T extends Comparable<T>> T minimum(T x,T y,T z) { T min = x; //assume x
is initially the min
if (y.compareTo(min) < 0)
min = y; // y is the min so far
if (z.compareTo(min) < 0)
min = z; // z is the min
return min; // returns the min object
}
public static void main(String args[]) {
System.out.printf("Minimum of %d, %d and %d is %d\n\n", 3,4,5, minimum(3,4,5));
System.out.printf("Minimum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7,
minimum(6.6,8.8,7.7));
System.out.printf("Minimum of %s, %s and %s is %s\n", "pear", "apple", "orange",
minimum("pear", "apple", "orange")); }
} Minimum of 3, 4 and 5 is 3
Minimum of 6.6, 8.8 and 7.7 is 6.6
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 27 Minimum of
pear, apple and orange is apple

Generic Methods: Minimum of


three objects

Program notes

Method compareTo whether predefined or
declared by the user must
Return 0 if the objects compared are equal
● ●

Return -1 if object1 is less than object2



Return 1 if object1 is greater than object2

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 28

Generic Classes

Provide a means for describing the concept
of a class in a type-independent manner

Can then instantiate type-specific objects of
the generic class

Example

Generic stack

We shall create a generic stack class
implemented as an array

Then test the class with doubles and integers

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 29

Generic Classes
package generics;
public class Stack <E> {
private int size; // number of elements in the stack private int top; // location of the top
element private E[] elements; // array that stores stack elements //no-argument
constructor creates a stack of the default size public Stack() {
this(10);
}
//constructor creates a stack of the specified number of elements public Stack(int s) {
size = s > 0 ? s : 10; // set size of Stack top = -1; // Stack initially
empty
elements = (E[]) new Object[size]; // create array }

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 30

Generic Classes
// push element onto stack; if successful, return true; // otherwise, throw
FullStackException
public void push(E pushValue) {
if (top == size - 1) // if stack is full
throw new FullStackException(String.format( "Stack is full, cannot push %s",
pushValue)); elements[++top] = pushValue; // place pushValue on Stack }
// return the top element if not empty; else throw EmptyStackException public E pop() {
if (top == -1) // if stack is empty
throw new EmptyStackException("Stack is empty, cannot pop"); return elements[top--]; // remove
and return top element of Stack }
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 31

Generic Classes
package generics;
public class FullStackException extends RuntimeException { public
FullStackException() {
this("Stack is full");
}
public FullStackException(String exception) { super(exception);
}
}

package generics;
public class EmptyStackException extends RuntimeException { public
EmptyStackException() {
this("Stack is empty");
}
public EmptyStackException(String exception)
{ super(exception);
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 32

Generic Classes
package generics;
public class StackTest {
private double[] doubleElements = {1.1,2.2,3.3,4.4,5.5,6.6}; private int[] integerElements =
{1,2,3,4,5,6,7,8,9,10,11}; private Stack <Double> doubleStack; //stack stores Double objects
private Stack <Integer> integerStack;//stack stores Integer objects // test Stack objects
public void testStacks() {
doubleStack = new Stack <Double>(5); //Stack of Doubles integerStack = new Stack
<Integer> (10); //Stack of Integers testPushDouble(); // push double onto doubleStack
testPopDouble(); // pop from doubleStack
testPushInteger(); // push int onto intStack
testPopInteger(); // pop from intStack
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 33

Generic Classes
// test push method with double stack
public void testPushDouble() {
try {
System.out.println("\nPushing elements onto doubleStack"); for (double element :
doubleElements) {
System.out.printf("%.1f ", element);
doubleStack.push(element); // push onto doubleStack }
}
catch (FullStackException fullStackException) { System.err.println();
fullStackException.printStackTrace();
}
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 34
Generic Classes
// test pop method with double stack
public void testPopDouble() {
try {
System.out.println("\nPopping elements from doubleStack"); double popValue;
// remove all elements from Stack
while (true) {
popValue = doubleStack.pop(); // pop from doubleStack System.out.printf("%.1f ",
popValue);
}
}
catch(EmptyStackException emptyStackException)
{ System.err.println();
emptyStackException.printStackTrace();
}
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 35
Generic Classes
// test push method with integer stack
public void testPushInteger() {
try {
System.out.println("\nPushing elements onto integerStack"); for (int element :
integerElements) {
System.out.printf("%d ", element);
integerStack.push(element); // push onto integerStack }
}
catch (FullStackException fullStackException) { System.err.println();
fullStackException.printStackTrace();
}
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 36
Generic Classes
// test pop method with integer stack
public void testPopInteger() {
// pop elements from stack
try {
System.out.println("\nPopping elements from integerStack"); int popValue;

// remove all elements from Stack


while (true) {
popValue = integerStack.pop();
System.out.printf("%d ", popValue);
}
}
catch(EmptyStackException emptyStackException) { System.err.println();
emptyStackException.printStackTrace();
}
}
public static void main(String args[]) {
StackTest application = new StackTest();
application.testStacks();
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 37
Generic Classes
Pushing elements onto doubleStack
generics.FullStackException: Stack is full, cannot push 6.6 1.1 2.2 3.3 4.4 5.5
6.6
Popping elements from doubleStack
5.5 4.4 3.3 2.2 1.1
Pushing elements onto integerStack
at generics.Stack.push(Stack.java:20)
at generics.StackTest.testPushDouble(StackTest.java:23) at
generics.StackTest.testStacks(StackTest.java:11)
at generics.StackTest.main(StackTest.java:81)
generics.EmptyStackException: Stack is empty, cannot pop 1 2 3 4 5 6 7 8
9 10 11
Popping elements from integerStack
at generics.Stack.pop(Stack.java:27)
at generics.StackTest.testPopDouble(StackTest.java:38)
at generics.StackTest.testStacks(StackTest.java:12)
at generics.StackTest.main(StackTest.java:81)
generics.FullStackException: Stack is full, cannot push 11 at
generics.Stack.push(Stack.java:20)
at generics.StackTest.testPushInteger(StackTest.java:53) at
generics.StackTest.testStacks(StackTest.java:13)
at generics.StackTest.main(StackTest.java:81)
generics.EmptyStackException: Stack is empty, cannot pop at
generics.Stack.pop(Stack.java:27)
at generics.StackTest.testPopInteger(StackTest.java:70) at
generics.StackTest.testStacks(StackTest.java:14)
at generics.StackTest.main(StackTest.java:81)
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 38 10 9 8 7
654321

Generic Classes

Class Stack Notes

Notice class name is followed by a type parameter section
<E>

elements is declared as an array of type E

But type parameters are not allowed as members of an array ●

Hence, create an array of type Object and cast the reference to


type E[]

Class EmptyStackException is used to throw an exception if
any attempt is made to read from an empty stack

Class FullStackException is used to throw an exception if
any attempt is made to write to a full stack
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 39

Generic Classes

Useful references on generics

https://docs.oracle.com/javase/tutorial/java/g
enerics/index.html

https://docs.oracle.com/javase/tutorial/extra/g
enerics/index.html
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 40

Outline

Data Structures

Type Wrapper Classes ●

Generic Programming ●

Collections
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 41

Java Collections Framework



Contains pre-packaged data structures,
interfaces, and algorithms for
manipulating the data structures

Programmers are able to use existing
data structures without concern for how
they are implemented
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 42

Java Collections Framework



Collection
An object that can hold references to other objects


Collections framework interfaces declare operations
to be performed generically on various types of
collections:

Set: collection that does not contain duplicates

List: ordered collection that can contain duplicate
elements

Queue: FIFO collection

Others
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 43

Java Collections Framework



Class Arrays

Provides static methods for manipulating
arrays

Examples
sort: for sorting an array

binarySearch: for searching a sorted array


● ●

equals for comparing arrays


fill for placing values into an array

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 44

Java Collections Framework


package generics;
import java.util.Arrays;
public class UsingArrays {
private int intArray[] = { 1, 2, 3, 4, 5, 6 };
private double doubleArray[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; private int filledIntArray[],
intArrayCopy[];
public UsingArrays() {
filledIntArray = new int[10]; //create int array with 10 elements intArrayCopy = new
int[intArray.length];
Arrays.fill(filledIntArray, 7); //fill with 7s
Arrays.sort(doubleArray); //sort doubleArray ascending // copy array intArray
into array intArrayCopy
System.arraycopy(intArray, 0, intArrayCopy,0, intArray.length); }
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 45

Java Collections Framework


// output values in each array
public void printArrays() {
System.out.print("doubleArray: "); for (double doubleValue :
doubleArray) System.out.printf("%.1f ", doubleValue);
System.out.print("\nintArray: ");
for (int intValue : intArray)
System.out.printf("%d ", intValue); System.out.print("\
nfilledIntArray: "); for (int intValue : filledIntArray)
System.out.printf("%d ", intValue); System.out.print("\
nintArrayCopy: "); for (int intValue : intArrayCopy)
System.out.printf("%d ", intValue); System.out.println("\
n");
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 46
Java Collections Framework
// find value in array intArray
public int searchForInt(int value){
return Arrays.binarySearch(intArray, value);
}
// compare array contents
public void printEquality() {
boolean b = Arrays.equals(intArray, intArrayCopy); System.out.printf("intArray %s
intArrayCopy\n", (b ? "==" : "!=")); b = Arrays.equals(intArray, filledIntArray);
System.out.printf("intArray %s filledIntArray\n", (b ? "==" : "!=")); }

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 47
Java Collections Framework

public static void main(String args[]) {


UsingArrays usingArrays = new UsingArrays();
usingArrays.printArrays();
usingArrays.printEquality();
int location = usingArrays.searchForInt(5);
if (location >= 0)
System.out.printf("Found 5 at element %d in intArray\n", location); else
System.out.println("5 not found in intArray"); location =
usingArrays.searchForInt(8763);
if (location >= 0)
System.out.printf("Found 8763 at element %d in intArray\n", location); else
System.out.println("8763 not found in intArray"); }
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 48
Java Collections Framework

doubleArray: 0.2 3.4 7.9 8.4 9.3 intArray: 1


23456
filledIntArray: 7 7 7 7 7 7 7 7 7 7 intArrayCopy:
123456

intArray == intArrayCopy
intArray != filledIntArray
Found 5 at element 4 in intArray 8763 not
found in intArray
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 49

Interface Collection and Class


Collections

These provide pre-defined objects and
powerful methods for manipulating
queues, sets, lists, and many other
collections
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 50

Interface Collection

Root interface in the collection hierarchy



Contains bulk operations (operations
performed on entire collections)

Clearing, comparing, retaining objects in a
collection

Converting a collection to an array

Provides a method that returns an Iterator object
which allows a program to walk through the
collection and remove elements from the
collection during the iteration
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 51

Class Collections

Provides static methods used to
manipulate collections polymorphically

Searching, sorting, etc.
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 52

Lists

An ordered Collection that can contain
duplicate elements

Provides methods for manipulating elements
via their indices, manipulating a range of
elements, searching for elements, getting a
ListIterator to access elements

Interface List

Implemented by several classes: LinkedList,
Vector, ArrayList, etc.
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 53

Class ArrayList, Vector, LinkedList



Class ArrayList and Vector
Resizable array implementations of interface List


Objects of class Vector are synchronized by default
(useful in multithreading); objects of class ArrayList are
not synchronized by default

ArrayList preferred over Vector in applications that do not
share a collection among threads because
unsynchronized collections provide better performance
than synchronized collections

Class LinkedList

Linked list implementation of interface List
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 54

ArrayList and Iterator Example


package generics;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest {
private static final String[] colors =
{ "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" }; private static
final String[] removeColors = { "RED", "WHITE", "BLUE" };
// create ArrayList, add Colors to it and manipulate it public CollectionTest() {
List <String> list = new ArrayList <String>(); List <String> removeList = new
ArrayList <String>(); // add elements in colors array to list
for (String color : colors)
list.add(color);
// add elements in removeColors to removeList for (String color :
removeColors)
removeList.add(color);
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 55
System.out.println("ArrayList: ");

ArrayList and Iterator Example


// output list contents
for (int count = 0; count < list.size(); count++) System.out.printf("%s ",
list.get(count));
// remove colors contained in removeList
removeColors(list, removeList);
System.out.println("\n\nArrayList after calling removeColors: "); // output list contents
for (String color : list) System.out.printf("%s ", color); }
// remove colors specified in collection2 from collection1 private void
removeColors(
Collection <String> collection1, Collection <String> collection2){ // get iterator
Iterator <String> iterator = collection1.iterator(); // loop while collection has
items
while (iterator.hasNext())
if (collection2.contains(iterator.next())) iterator.remove(); }
public static void main(String args[]){
new CollectionTest(); } ArrayList:
} MAGENTA RED WHITE BLUE CYAN ArrayList
after calling removeColors:
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 56
MAGENTA CYAN

ArrayList and Iterator Example



Program Notes

ArrayList is generic class, and so we specify
type argument (String in this program) to
indicate the type of element in each list

Interface Collection provides the iterator
method that returns an iterator object

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 57
LinkedList Example 1

Creates two Linkedlists that contain
Strings
Elements of one List added to another
– –

Strings converted to uppercase Range


of elements deleted from list


May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 58

LinkedList Example 1

package generics;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class ListTest {
private static final String colors[] = { "black", "yellow", "green", "blue", "violet",
"silver" };
private static final String colors2[] = { "gold", "white", "brown", "blue", "gray",
"silver" };
// set up and manipulate LinkedList objects
public ListTest(){
List <String> list1 = new LinkedList <String>(); List <String> list2 = new
LinkedList <String>();
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 59

LinkedList Example 1
// add elements to list link
for (String color : colors)
list1.add(color);
// add elements to list link2
for (String color : colors2)
list2.add(color);
list1.addAll(list2); // concatenate lists
list2 = null; // release resources
printList(list1);
convertToUppercaseStrings(list1); //convert to upper case printList(list1);
System.out.print("\nDeleting elements 4 to 6..."); removeItems(list1, 4, 7); //
remove items 4-7 from list printList(list1); // print list1 elements
printReversedList(list1); // print list in reverse order }

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 60
LinkedList Example 1
// output List contents
public void printList(List <String> list){
System.out.println("\nlist: ");
for (String color : list)
System.out.printf("%s ", color);
System.out.println();
}
// locate String objects and convert to uppercase private void
convertToUppercaseStrings(List <String> list){ ListIterator <String> iterator =
list.listIterator(); while (iterator.hasNext()) {
String color = iterator.next(); // get item iterator.set(color.toUpperCase()); //convert to
upper case }
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 61
LinkedList Example 1
//obtain sublist and use clear method to delete sublist items private void
removeItems(List <String> list, int start, int end){ list.subList(start, end).clear(); // remove
items }
// print reversed list
private void printReversedList(List <String> list){ //iterator below is a bidirectional
iterator ListIterator <String> iterator = list.listIterator(list.size()); System.out.println("\
nReversed List:");
while (iterator.hasPrevious())
System.out.printf("%s ", iterator.previous()); }
public static void main(String args[]){
new ListTest();
}
}

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 62
LinkedList Example 1

list:
black yellow green blue violet silver gold white brown blue gray silver

list:
BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER

Deleting elements 4 to 6...


list:
BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER

Reversed List:
SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 63

LinkedList Example 2

Creating a LinkedList with a List view of an array
Idea


Previous example used a loop to add the contents of
an array one by one to the list

Here, we want to pass array content onto list at the
time the list object is created

But an array cannot be passed as a parameter to a
LinkedList constructor

So we pass the array asList to the constructor

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 64
LinkedList Example 2

Program notes

Method asList used to view an array as a List
collection

Method toArray used to get an array from a
LinkedList collection
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 65

LinkedList Example 2
package csc308.generics;
import java.util.*;
public class UsingToArray {
// create LinkedList, add elements and convert to array public
UsingToArray(){
String colors[] = {"black", "blue", "yellow"}; LinkedList links = new
LinkedList(Arrays.asList(colors)); links.addLast( "red"); // add as last item
links.add("pink"); // add to the end
links.add(3,"green"); // add at 3rd index
links.addFirst("cyan"); // add as first item // get LinkedList
elements as an array
colors=(String []) links.toArray(new String[links.size()]);
System.out.println( "colors: " ); }
for (int count = 0; count < colors.length; colors: cyan
count++) System.out.println(colors[ count ]); black
} blue
public static void main(String args[]){ yellow
new UsingToArray(); green
red
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 66
} // end class UsingToArray pink

Collection Algorithms

Several high-performance algorithms for
manipulating collection elements
Implemented as static methods of class

Collections
Algorithms sort, binarySearch, reverse,

shuffle, fill and copy operate on Lists



Algorithms min, max, addAll, frequency and
disjoint operate on Collections
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 67

Sort Example 1
package generics;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Sort1 {
private static final String suits[] =
{"Hearts", "Diamonds", "Clubs", "Spades"};
// display array elements
public void printElements() {
List <String> list = Arrays.asList(suits); // output list
System.out.printf("Unsorted array elements:\n%s\n", list); Collections.sort(list);
System.out.printf("Sorted array elements:\n%s\n", list); }

May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 68
Sort Example 1
public static void main(String args[])
{ System.out.print("Original Array: "); for (String s : suits)
System.out.printf("%s ",s); System.out.println();
Sort1 sort1 = new Sort1();
sort1.printElements();
System.out.print("Final Array: "); for (String s : suits)
System.out.printf("%s ",s); System.out.println();
}
}Original Array: Hearts Diamonds Clubs Spades Unsorted
array elements:
[Hearts, Diamonds, Clubs, Spades]
Sorted array elements:
[Clubs, Diamonds, Hearts, Spades]
Final Array: Clubs Diamonds Hearts Spades
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 69
Sort Example 1

Program Notes

Method asList used to view an array as a List
collection
Collections method sort used to sort the list
– –

Changes to the list write through to the array



As observed with list and array outputs after
sorting
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 70

Sort Example 2
package generics;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Sort2 {
private static final String suits[] =
{"Hearts", "Diamonds", "Clubs", "Spades"};
// display array elements
public void printElements() {
//Fixed-size list backed by an array
//Changes to the returned list "write through" to the array List <String> list =
Arrays.asList(suits);
// output list
System.out.printf("Unsorted array elements:\n%s\n", list); Collections.sort(list,
Collections.reverseOrder()); System.out.printf("Sorted array elements:\n%s\n", list);
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 71

Sort Example 2
public static void main(String args[])
{ System.out.print("Original Array: "); for (String s : suits)
System.out.printf("%s ",s); System.out.println();
Sort2 sort2 = new Sort2();
sort2.printElements();
System.out.print("Final Array: "); for (String s : suits)
System.out.printf("%s ",s); System.out.println();
}
}
Original Array: Hearts Diamonds Clubs Spades Unsorted
array elements:
[Hearts, Diamonds, Clubs, Spades]
Sorted array elements:
[Spades, Hearts, Diamonds, Clubs]
Final Array: Spades Hearts Diamonds Clubs
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 72
Sort Example 2 (Descending Order)

This time, list is sorted in descending
order, and not the default ascending
order

Notice the line in bold

The additional parameter
Collections.reverseOrder()

Collection method reverseOrder() returns a
Comparator object that orders the collection’s
elements in reverse order
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 73

Sorting with a Comparator



You can create your own comparator
class that determines how to compare
any two objects

Example class compares two time objects

Implements interface Comparator based on
the Time2 class we saw earlier on in the
semester
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 74

Sorting with a Comparator


package csc308.generics;
import java.util.Comparator;
public class TimeComparator implements Comparator<Time2> { public int
compare(Time2 time1, Time2 time2) { //compare hour
int hourCompare = time1.getHour() - time2.getHour(); // test hour first
if (hourCompare != 0)
return hourCompare;
int minuteCompare =
time1.getMinute() - time2.getMinute(); // compare minute // then test minute
if (minuteCompare != 0)
return minuteCompare;
int secondCompare =
time1.getSecond() - time2.getSecond(); // compare second return
secondCompare; // return result of comparing second } // end of method compare
} // end of class TimeComparator
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 75

Sorting with a Comparator


package time2;
public class Time2 {
private int hour; //0-23
private int minute; //0-59
private int second; //0-59
public Time2() { this(0,0,0); } public Time2(int h) { this(h,0,0); } public
Time2(int h, int m) { this(h,m,0); } public Time2(int h, int m, int s) { setTime(h,
m, s); } public Time2(Time2 time){
this(time.getHour(),time.getMinute(),time.getSecond()); }
public void setTime(int h, int m, int s) {
setHour(h); setMinute(m); setSecond(s);
}
public void setHour(int h) { hour = ((h >= 0 && h < 24) ? h : 0); } public void setMinute(int m)
{ minute = ((m >= 0 && m < 60) ? m : 0); } public void setSecond(int s) { second = ((s >= 0 && s <
60) ? s : 0); } public int getHour() { return hour; }
public int getMinute(){ return minute; }
public int getSecond(){ return second; }
public String toUniversalString() {
return String.format("%02d:%02d:%02d", hour,minute,second); }
public String toString(){
return String.format("%d:%02d:%02d %s", ((hour == 0 || hour == 12)? 12 : hour % 12),
minute,second, (hour < 12 ? "AM" : "PM"));
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 76 }

Sorting with a Comparator


package csc308.generics;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Sort3 {
public void printElements() {
List< Time2 > list = new ArrayList< Time2 >(); // create List list.add(new Time2(6,24,34));
list.add(new Time2(18,14,58)); list.add(new Time2(6,05,34)); list.add(new
Time2(12,14,58)); list.add(new Time2(6,24,22));
// output List elements
System.out.printf( "Unsorted array elements:\n%s\n", list );
// sort in order using a comparator
Collections.sort( list, new TimeComparator() );
// output List elements
System.out.printf( "Sorted list elements:\n%s\n", list ); } // end method printElements
public static void main( String args[] ) {
Sort3 sort3=new Sort3();
sort3.printElements();
Unsorted array elements:
} // end main [6:24:34 AM, 6:14:58 PM, 6:05:34 AM, 12:14:58 PM, 6:24:22
AM] Sorted list elements:
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 77
} // end class Sort3
[6:05:34 AM, 6:24:22 AM, 6:24:34 AM, 12:14:58 PM, 6:14:58 PM]
Search Example
package generics;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
public class BinarySearchTest {
private static final String colors[] = {"red", "white", "blue", "black", "yellow",
"purple", "tan", "pink"}; private List <String> list;
// create, sort and output list
public BinarySearchTest() {
list = new ArrayList <String>(Arrays.asList(colors)); Collections.sort(list); // sort
the ArrayList System.out.printf("Sorted ArrayList: %s\n", list); }
private void search() {
printSearchResults(colors[3]);
printSearchResults(colors[0]);
printSearchResults(colors[7]);
printSearchResults("aqua");
printSearchResults("gray");
printSearchResults("teal");
} May 25, 2022 D. L. Nkweteyim - CSC 308 (Java
Programming - DS & Generics) 78

Search Example
private void printSearchResults(String key) { int result = 0;
System.out.printf("\nSearching for: %s\n", key); result =
Collections.binarySearch(list, key);

if (result >= 0) {
System.out.printf("Found at index %d\n", result); } else {
System.out.printf("Not Found (%d)\n", result); }
}

public static void main(String args[]) {


BinarySearchTest binarySearchTest = new BinarySearchTest();
binarySearchTest.search();
}
}
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 79
Search Example
Sorted ArrayList: [black, blue, pink, purple, red, tan, white, yellow]

Searching for: black


Found at index 0

Searching for: red


Found at index 4

Searching for: pink


Found at index 2

Searching for: aqua


Not Found (-1)

Searching for: gray


Not Found (-3)

Searching for: teal


Not Found (-7)
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 80

You might also like