Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set--...

35
Collections in Java

Transcript of Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set--...

Page 1: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Collections in Java

Page 2: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Kinds of Collections

• Collection--a group of objects, called elements– Set--An unordered collection with no duplicates

•SortedSet--An ordered collection with no duplicates

– List--an ordered collection, duplicates are allowed

• Map--a collection that maps keys to values– SortedMap--a collection ordered by the keys

• Note that there are two distinct hierarchies

Page 3: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Using Collections

• import java.util.*or import java.util.Collection;

• There is a sister class, java.util.Collections; that provides a number of algorithms for use with collections: sort, binarySearch, copy, shuffle, reverse, max, min, etc.

Page 4: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Collections are interfaces

• Collection is actually an interface

• Each kind of Collection has one or more implementations

• You can create new kinds of Collections

• When you implement an interface, you promise to supply the required methods

• Some Collection methods are optional

Page 5: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Creating a Collection

• All Collection implementations should have two constructors:– A no-argument constructor to create an empty

collection– A constructor with another Collection as

argument

• Cannot be enforced, because an Interface cannot specify constructors

Page 6: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Collection: Basic operations

• int size( );• boolean isEmpty( );• boolean contains(Object element);• boolean add(Object element); //

Optional• boolean remove(Object element); //

Optional• Iterator iterator( );

Page 7: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Collection: Iterator

boolean hasNext( );// true if there is another element

Object next( );// returns the next element (advances the iterator)

void remove( ); // Optional // removes the element returned by next}

public interface Iterator {

Page 8: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Using an Iterator

• static void printAll (Collection c) { Iterator i = c.iterator( ); while (i.hasNext( )) { System.out.println ( i.next( ) ); } }

• Note that this code is polymorphic--it will work for any collection

Page 9: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Iterator vs. Enumeration

• Iterators are better than the old Enumerations– It is safe to remove objects with an Iterator– The names have been improved:

– Enumeration IteratorhasMoreElements( ) hasNext( )nextElement( ) next( )can’t remove remove( )

Page 10: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Collection: Bulk operations

• boolean containsAll(Collection c);• boolean addAll(Collection c); // Optional• boolean removeAll(Collection c); // Optional• boolean retainAll(Collection c); // Optional• void clear( ); // Optional

• addAll, removeAll, retainAll return true if the object receiving the message was modified

Page 11: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Mixing Collection types

• Note that most methods, such as boolean containsAll(Collection c); are defined for any type of Collection, and take any type of Collection as an argument.

• This makes it very easy to work with different types of Collections.

Page 12: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

singleton

• Collections.singleton(e) returns an immutable set containing only the element e

• c.removeAll(Collections.singleton(e)); will remove all occurrences of e from the Collection c

Page 13: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Collection: Array operations

• Object[ ] toArray( );– creates a new array of Object

• Object[ ] toArray(Object a[ ]);– Allows the caller to provide the array

• Examples:

– Object[ ] a = c.toArray( );– String[ ] a;

a = (String[ ]) c.toArray(new String[0]);

Page 14: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

The Set interface

• A Set is unordered and has no duplicates

• Operations are exactly those for Collections

int size( );boolean isEmpty( );boolean contains(Object e);boolean add(Object e); boolean remove(Object e); Iterator iterator( );

boolean containsAll(Collection c);boolean addAll(Collection c); boolean removeAll(Collection c);boolean retainAll(Collection c);void clear( );Object[ ] toArray( );Object[ ] toArray(Object a[ ]);

Page 15: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Set implementations

• Set is an interface; you can’t say new Set ( )• There are two implementations:

– HashSet is best for most purposes

– TreeSet guarantees the order of iteration

• It’s poor style to expose the implementation, so:

• Good: Set s = new HashSet( );Bad: HashSet s = new HashSet( );

Page 16: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Typical set operations

• Testing if s2 is a subset of s1 s1.containsAll(s2)

• Setting s1 to the union of s1 and s2 s1.addAll(s2)

• Setting s1 to the intersection of s1 and s2 s1.retainAll(s2)

• Setting s1 to the set difference of s1 and s2 s1.removeAll(s2)

Page 17: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Set equality

• Object.equals(Object), inherited by all objects, really is an identity comparison

• Implementations of Set override equals so that sets are equal if they contain the same elements

• equals even works if two sets have different implementations

• hashCode has been extended similarly

Page 18: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Set tips

• add and remove return true if they modify the set

• Here's a trick to remove duplicates from a Collection c:– Collection noDups = new HashSet(c);

• A Set may not contain itself an an element

• Danger: undefined behavior if you change an element to be equal to another element

Page 19: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

The SortedSet interface

• A SortedSet is just like a Set, except that an Iterator will go through it in a guaranteed order

• Implemented by TreeSet

Page 20: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

The List interface

• A List is ordered and may have duplicates

• Operations are exactly those for Collections

int size( );boolean isEmpty( );boolean contains(Object e);boolean add(Object e); boolean remove(Object e); Iterator iterator( );

boolean containsAll(Collection c);boolean addAll(Collection c); boolean removeAll(Collection c);boolean retainAll(Collection c);void clear( );Object[ ] toArray( );Object[ ] toArray(Object a[ ]);

Page 21: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List implementations

• List is an interface; you can’t say new List ( )• There are two implementations:

– LinkedList gives faster insertions and deletions

– ArrayList gives faster random access

• It’s poor style to expose the implementation, so:

• Good: List list = new LinkedList ( );Bad: LinkedList list = new LinkedList ( );

Page 22: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Inherited List methods

• list.remove(e) removes the first e• add and addAll add to the end of the list• To append one list to another:

– list1.addAll(list2);

• To append two lists into a new list:– List list3 = new ArrayList(list1);

list3.addAll(list2);

• Again, it's good style to hide the implementation

Page 23: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List: Positional access

• Object get(int index); // Required -- // the rest are optional

• Object set(int index, Object element); • void add(int index, Object element); • Object remove(int index); • abstract boolean addAll(int index, Collection

c); • These operations are more efficient with the ArrayList

implementation

Page 24: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List: Searching

• int indexOf(Object o);• int lastIndexOf(Object o);

• equals and hashCode work even if implementations are different

Page 25: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List: Iteration

• ListIterator listIterator( );• ListIterator listIterator(int index);

– starts at the position indicated (0 is first element)

• Inherited methods:– boolean hasNext( );– Object next( );– void remove( );

Page 26: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List: Iterating backwards

• boolean hasPrevious( );• Object previous( );• int nextIndex( );• int previousIndex( );• Think of the iterator as “between” elements

• Hence, next followed by previous gives you the same element each time

Page 27: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List: More operations

• void add(Object o); – Inserts an object at the cursor position

• Object set(Object o); // Optional– Replace the current element; return the old one

• Object remove(int index); // Optional– Remove and return the element at that position

Page 28: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

List: Range-view

• List subList(int from, int to); allows you to manipulate part of a list

• A sublist may be used just like any other list

Page 29: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

The Map interface

• A Map is an object that maps keys to values

• A map cannot contain duplicate keys

• Each key can map to at most one value

• Examples: dictionary, phone book, etc.

Page 30: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Map implementations

• Map is an interface; you can’t say new Map ( )• Here are two implementations:

– HashMap is the faster

– TreeMap guarantees the order of iteration

• It’s poor style to expose the implementation, so:• Good: Map map = new HashMap ( );

Bad: HashMap map = new HashMap ( );

Page 31: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Map: Basic operations

• Object put(Object key, Object value);• Object get(Object key);• Object remove(Object key);• boolean containsKey(Object key);• boolean containsValue(Object value);• int size( );• boolean isEmpty( );

Page 32: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Map: Bulk operations

• void putAll(Map t);– copies one Map into another

• void clear();

Page 33: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Map: Collection views

• public Set keySet( );• public Collection values( );• public Set entrySet( );

– returns a set of Map.Entry (key-value) pairs

• The above views provide the only way to iterate over a Map

Page 34: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

Map.Entry: Interface for entrySet elements

• public interface Entry { Object getKey( ); Object getValue( ); Object setValue(Object value);}

• This is a small interface for working with the Collection returned by entrySet( )

• Can get elements only from the Iterator, and they are only valid during the iteration

Page 35: Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.

The End

http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html