Professional Documents
Culture Documents
CSC308 Second Semester 2021-2022 Part 6 - Data Structures and Generic Programming
CSC308 Second Semester 2021-2022 Part 6 - Data Structures and Generic Programming
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
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 8
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
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
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
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
Outline
●
Data Structures
–
Type Wrapper Classes ●
Generic Programming ●
Collections
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 18
●
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:
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
–
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
–
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
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 26
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;
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 ●
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
–
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
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
May 25, 2022 D. L. Nkweteyim - CSC 308 (Java Programming - DS & Generics) 48
Java Collections Framework
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
●
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
–
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
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
– –
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
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,
–
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
– –
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
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); }
}