0% found this document useful (0 votes)
43 views20 pages

Java Collections: Object-Oriented Programming

This document provides an overview of Java Collections and common data structures like lists, sets, iterators, and trees. It discusses the collection class hierarchy in Java and shows examples of using lists, sets, sorted sets, and iterators to traverse and manipulate collection data. Key points covered include the Collection interface, List and Set interfaces and implementations like ArrayList and HashSet, and SortedSet functionality in TreeSet.

Uploaded by

ankitgaur36
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views20 pages

Java Collections: Object-Oriented Programming

This document provides an overview of Java Collections and common data structures like lists, sets, iterators, and trees. It discusses the collection class hierarchy in Java and shows examples of using lists, sets, sorted sets, and iterators to traverse and manipulate collection data. Key points covered include the Collection interface, List and Set interfaces and implementations like ArrayList and HashSet, and SortedSet functionality in TreeSet.

Uploaded by

ankitgaur36
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Java Collections

Java Collections
Object-oriented programming

Inf1 :: 2005

Object-oriented programming

Java Collections

Java Collections

Collections

Data structures like the ones we discussed in the previous lectures are so important that the Java library provided a generic implementation
Package java.util

The collections framework is a perfect example of polymorphism, interfaces and object-oriented design
There is a basic interface (Collection) that all classes in java.util implement Behaviours are implemented in a variety of ways

We will deal with lists, sets, iterators and trees

Object-oriented programming

Java Collections

Java Collections

The class/interface hierarchy


Iterator Collection boolean isEmpty () boolean add/remove (Object o) boolean add/removeAll (Collection c) void clear () boolean contains (Object o) boolean containsAll (Collection c) Iterator iterator () int size () Object [] toArray () Set boolean hasNext () Object next () void remove () ListIterator boolean hasPrevious () Object previous () int nextIndex () int previousIndex () List Object get (int index) Object set (int index, Object o) void add (int index, Object o) void addAll (int index, Collection c) Object remove (int index) int indexOf (Object o) int lastIndexOf (Object o) ListIterator listIterator () ListIterator listIterator (int index) List subList (int start, int end) AbstractList TreeSet HashSet void removeRange (int start, int end) AbstractSequentialList

Comparator int compare (Object o1, Object o2)

SortedSet Comparator comparator () Object rst () Object last () SortedSet headSet (Object to) SortedSet tailSet (Object from) SortedSet subset (Object from, Object to) AbstractSet

LinkedList Object getFirst () Object getLast () void addFirst (Object o) void addLast (Object o) Object removeFirst () Object removeLast ()

ArrayList void ensureCapacity (int min) void trimToSize ()

Object-oriented programming

Java Collections

Java Collections

In more detail
Collections are either Lists or Sets Lists are
Sequential Possibly with duplicate values Unordered with respect to the values they store

Sets are
Unordered with respect to the values Without any duplicate values

SortedSets are
Ordered (with respect to their values) Sets

Iterators are
A way of traversing all values in a Collection

ListIterators are
Special Iterators that allow one to traverse sequential Collections like Lists
Object-oriented programming Java Collections

Java Collections

Using a List
import everything from the java.util package (the collections framework)

import java.util.*; public class ListTest {

private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public ListTest () { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.print("\nList: "); printList(list); System.out.print("\nReversed List: "); printReversedList(list); System.out.print("\nList from 5, forward: "); printListFromIndex(5, list); System.out.print("\nList from 5, backward: "); printReversedListFromIndex(5, list); }

List interface make the reference aim at a class that implements the interface (ArrayList) polymorphism ArrayLists implementation of add() will be called; add() is a Collection method and List extends Collection

Object-oriented programming

Java Collections

Java Collections

Traversing a List with an Iterator

public void printList (List l) { Iterator iter = l.iterator();

iterator declare an Iterator over the List, i.e., obtain a sequential handle over the Lists data; iterator() returns a ListIterator, which is an Iterator forward scan keep scanning forward, as long as the Iterator says there are more elements

list iterator declare a ListIterator over the List, since we want the extra functionality of scanning from a specic point
}

while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println();

public void printReversedList (List l) { ListIterator iter = l.listIterator(l.size()); while (iter.hasPrevious()) System.out.print(iter.previous() + " "); System.out.println(); }

backward scan keep scanning backwards, as long as the ListIterator says there are more elements

Object-oriented programming

Java Collections

Java Collections

Using a List results


import java.util.*; public class ListTest { private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public ListTest () { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.print("\nList: "); printList(list); System.out.print("\nReversed List: "); printReversedList(list); System.out.print("\nList from 5, forward: "); printListFromIndex(5, list); System.out.print("\nList from 5, backward: "); printReversedListFromIndex(5, list); }

List: red white blue green gray orange tan white cyan peach gray orange Reversed List: orange gray peach cyan white tan orange gray green blue white red List from 5, forward: orange tan white cyan peach gray orange List from 5, backward: gray green blue white red

Object-oriented programming

Java Collections

Java Collections

Using a Set
import java.util.* imports the Collections framework

import java.util.*; public class SetTest {

private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public SetTest () { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.print("\nArrayList: "); printCollection(list); Set hashSet = new HashSet(list); System.out.print("\nHashSet: "); printCollection(hashSet); }

reference to concrete class assign a List (interface) reference to an ArrayList concrete class (that implements the interface) create a set from a list use a Set (interface) reference to a HashSet concrete class (that implements the interface); use a list as the input collection

Object-oriented programming

Java Collections

Java Collections

Traversing a Set

Collection as parameter this will work for both Lists and Sets since they both extend Collection
public void printCollection (Collection c) { Iterator iter = c.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); }

Object-oriented programming

Java Collections

Java Collections

Using s Set results


import java.util.*; public class SetTest { private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public SetTest () { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.print("\nArrayList: "); printCollection(list); Set hashSet = new HashSet(list); System.out.print("\nHashSet: "); printCollection(hashSet); }

ArrayList: red white blue green gray orange tan white cyan peach gray orange HashSet: red cyan white tan gray green orange blue peach

Object-oriented programming

Java Collections

Java Collections

Using a SortedSet
import java.util.*; public class SortedSetTest { private static final String names[] = { "yellow", "green", "black", "tan", "grey", "white", "orange", "red", "green" }; public SortedSetTest () { SortedSet set = new TreeSet (); for (int i = 0; i < names.length; i++) set.add(names[i]); System.out.print("\nset: "); printSet(set); System.out.print("\nheadSet(\"orange\"): "); printSet(set.headSet("orange")); System.out.print("\ntailSet(\"orange\"): "); printSet(set.tailSet("orange")); System.out.print("\nheadSet(\"foo\"): "); printSet(set.headSet("foo")); System.out.print("\ntailSet(\"foo\"): "); printSet(set.tailSet("foo")); System.out.print("\nfirst: "); System.out.println(set.first()); System.out.print("\nlast: "); System.out.println(set.last()); }

polymorphism TreeSet implements SortedSet

SortedSet behaviour the methods called are SortedSet methods, but TreeSets implementations will be called

Object-oriented programming

Java Collections

Java Collections

Traversing a SortedSet through an Iterator

SortedSet reference though a TreeSet instance will be passed as a parameter by the caller
public void printSet (SortedSet set) { Iterator iter = set.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); }

Collection behaviour a SortedSet is still a Collection so we can have an Iterator over it

Object-oriented programming

Java Collections

Java Collections

Using s SortedSet results


import java.util.*; public class SortedSetTest { private static final String names[] = { "yellow", "green", "black", "tan", "grey", "white", "orange", "red", "green" }; public SortedSetTest () { SortedSet set = new TreeSet (); for (int i = 0; i < names.length; i++) set.add(names[i]); System.out.print("\nset: "); printSet(set); System.out.print("\nheadSet(\"orange\"): "); printSet(set.headSet("orange")); System.out.print("\ntailSet(\"orange\"): "); printSet(set.tailSet("orange")); System.out.print("\nheadSet(\"foo\"): "); printSet(set.headSet("foo")); System.out.print("\ntailSet(\"foo\"): "); printSet(set.tailSet("foo")); System.out.print("\nfirst: "); System.out.println(set.first()); System.out.print("\nlast: "); System.out.println(set.last()); }

set: black green grey orange red tan white yellow headSet("orange"): black green grey tailSet("orange"): orange red tan white yellow headSet("foo"): black tailSet("foo"): green grey orange red tan white yellow first: black last: yellow

Object-oriented programming

Java Collections

Java Collections

Classes Arrays and Collections

Provide generic implementations of certain functions Static method calls to invoke desired behaviour
Arrays.sort(array , value) Arrays.binarySearch(array , value) Collections.sort(Collection c) Collections.binarySearch(Collection c , Object o)

We will focus on Collections

Object-oriented programming

Java Collections

Java Collections

Sorting and searching a List

Carried out with the aid of an object that implements the Comparator interface Main comparison method is: int compare (Object o1, Object o2)
If o1 < o2, then return a negative integer If o1 == o2, then return zero If o1 > o2, then return a positive integer

Object-oriented programming

Java Collections

Java Collections

A Time class
import java.text.DecimalFormat; public class Time { private int hour; private int minute; private int second; public Time () { this(0, 0, 0); } public Time (int h) { this(h, 0, 0); } public Time (int h, int m) { this(h, m, 0); } public Time (int h, int m, int s) { setTime(h, m, s); } 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 toString () { DecimalFormat twoDigits = new DecimalFormat("00"); return twoDigits.format(hour) + ":" + twoDigits.format(minute) + ":" + twoDigits.format(second); } }

Object-oriented programming

Java Collections

Java Collections

A TimeComparator class
import simply import the necessary interface
import java.util.Comparator; public class TimeComparator implements Comparator { public TimeComparator () {} public int compare (Object o1, Object o2) { Time t1 = (Time) o1; Time t2 = (Time) o2; int comp = (t1.getHour() - t2.getHour()); if (comp != 0) return comp; comp = (t1.getMinute() - t2.getMinute()); if (comp != 0) return comp; comp = (t1.getSecond() - t2.getSecond()); return comp; } }

implementation specify which interface is implemented and provide an implementation for the methods of the interface cast TimeComparator can only handle Time objects; cast the parameters to Time (anything else will be a runtime error)

comparison make the comparison, at all times abiding by the semantics of the interface
Object-oriented programming Java Collections

Java Collections

Sorting a List of Time objects


import java.util.*; public class CollectionSortTest { public static void main (String args []) { List list = new ArrayList(); list.add(new list.add(new list.add(new list.add(new list.add(new Time( 6, Time(18, Time( 8, Time(12, Time( 6, 24, 34)); 14, 5)); 05, 0)); 07, 58)); 14, 22));

System.out.print("unsorted list is: "); System.out.println(list); Collections.sort(list, new TimeComparator()); System.out.print("sorted list is: "); System.out.println(list); } }

static call Collections.sort() is a static method

TimeComparator passed as the argument to sort(); becomes the sorting criterion

unsorted list is: [06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22] sorted list is: [06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05]

Object-oriented programming

Java Collections

Java Collections

Sorting and searching a List of String objects


import java.util.*; public class CollectionSearchTest { private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public static void main (String args []) { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.println("unsorted list: " + list); Collections.sort(list); System.out.println("sorted list: " + list);

no need for a Comparator the class of the objects inserted in the list (String), already implements the Comparator interface Collections.binarySearch() pass a list and the object were looking for and were done!

int p = Collections.binarySearch(list, "gray"); System.out.println("gray first appears in position: " + p);

p = Collections.binarySearch(list, "maroon"); System.out.println("maroon first appears in position: " + p); } }

unsorted list: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange] sorted list: [blue, cyan, gray, gray, green, orange, orange, peach, red, tan, white, white] gray first appears in position: 2 maroon first appears in position: -6

Object-oriented programming

Java Collections

Java Collections

Things to do

To do Read Deitel & Deitel, Sections 22.1, 22.2, 22.4, 22.5, 22.7 Become accustomed with the Java Collections framework Spend some time thinking on the differences between the various interfaces and classes

Object-oriented programming

Java Collections

You might also like