Collections in Java: Arrays
Collections in Java: Arrays
Collections in Java: Arrays
Arrays
n
Has special language support Iterator (i) Collection (i) Set (i),
u
Iterators
n
HashSet (c), TreeSet (c) ArrayList (c), LinkedList (c) HashMap (c), TreeMap (c)
List (i),
u
Map (i),
u
OOP: Collections
Array
Most efficient way to hold references to objects.
data index
Car Car
0 1 2
Car
3 4 5
Car
6 7
Advantages
n n n
An array know the type it holds, i.e., compile-time type checking. An array know its size, i.e., ask for the length. An array can hold primitive types directly. An array can only hold one type of objects (including primitives). Arrays are fixed size.
2
Disadvantages
n n
OOP: Collections
Array, Example
class Car{}; Car[] cars1; Car[] cars2 = new Car[10]; // minimal dummy class // null reference // null references
for (int i = 0; i < cars2.length; i++) cars2[i] = new Car(); // Aggregated initialization Car[] cars3 = {new Car(), new Car(), new Car(), new Car()}; cars1 = {new Car(), new Car(), new Car()};
Search and sort: binarySearch(), sort() Comparison: equals() (many overloaded) Instantiation: fill() (many overloaded) Conversion: asList()
3
OOP: Collections
Overview of Collection
A collection is a group of data manipulate as a single object.
Corresponds to a bag.
Like C++'s Standard Template Library (STL) Can grow as necessary. Contain only Objects (reference types). Heterogeneous. Can be made thread safe (concurrent access). Can be made not-modifiable.
4
OOP: Collections
Collection Interfaces
Collections are primarily defined through a set of interfaces.
n
[Source: java.sun.com]
Programs that uses an interface is not tightened to a specific implementation of a collection. It is easy to change or replace the underlying collection class with another (more efficient) class that implements the same interface.
5
OOP: Collections
OOP: Collections
[Source: bruceeckel.com]
list
Exception thrown if collection is modified externally, i.e., not via the iterator (multi-threading).
OOP: Collections
// an example public static void main (String[] args){ ArrayList cars = new ArrayList(); for (int i = 0; i < 12; i++) cars.add (new Car()); Iterator it = cats.iterator(); while (it.hasNext()) System.out.println ((Car)it.next()); }
OOP: Collections
Interface is identical. Every constructor must create a collection without duplicates. The operation add cannot add an element already in the set. The method call set1.equals(set2) works at follows
u
OOP: Collections
10
Set Idioms
set1 set2
n
set1 set2
n
set1 set2
n
OOP: Collections
11
Implemented using a hash table. No ordering of elements. add, remove, and contains methods constant time complexity O(c).
TreeSet
n n n
Implemented using a tree structure. Guarantees ordering of elements. add, remove, and contains methods logarithmic time complexity O(log (n)), where n is the number of elements in the set.
12
OOP: Collections
HashSet, Example
// [Source: java.sun.com] import java.util.*; public class FindDups { public static void main(String args[]){ Set s = new HashSet(); for (int i = 0; i < args.length; i++){ if (!s.add(args[i])) System.out.println("Duplicate detected: " + args[i]); } System.out.println(s.size() + " distinct words detected: " + s); } }
OOP: Collections
13
add (int, Object), get(int), remove(int), set(int, Object) (note set = replace bad name for the method) indexOf(Object), lastIndexOf(Object)
n n
OOP: Collections
14
add(Object)adds at the end of the list. remove(Object)removes at the start of the list. list1.equals(list2)the ordering of the elements is
taken into consideration. Extra requirements to the method hashCode.
n
OOP: Collections
15
}
OOP: Collections 16
Gives better performance on add and remove compared to ArrayList. Gives poorer performance on get and set methods compared to ArrayList.
OOP: Collections
17
ArrayList, Example
// [Source: java.sun.com] import java.util.*; public class Shuffle { public static void main(String args[]) { List l = new ArrayList(); for (int i = 0; i < args.length; i++) l.add(args[i]); Collections.shuffle(l, new Random()); System.out.println(l); } }
OOP: Collections
18
LinkedList, Example
import java.util.*; public class MyStack { private LinkedList list = new LinkedList(); public void push(Object o){ list.addFirst(o); } public Object top(){ return list.getFirst(); } public Object pop(){ return list.removeFirst(); } public static void main(String args[]) { Car myCar; MyStack s = new MyStack(); s.push (new Car()); myCar = (Car)s.pop(); } }
OOP: Collections 19
OOP: Collections
20
put(Object key, Object value) remove (Object key) get (Object key)
Methods to retrieve the keys, the values, and (key, value) pairs
n n n
OOP: Collections
22
HashMap
n n
TreeMap
n n
The implementation is based on red-black tree structure. (key, value) pairs are ordered on the key.
OOP: Collections
23
HashMap, Example
import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i < args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size()+ " distinct words detected:"); System.out.println(m); } }
OOP: Collections
24
Search and sort: binarySearch(), sort() Reorganization: reverse(), shuffle() Wrappings: unModifiableCollection, synchonizedCollection
OOP: Collections
25
OOP: Collections
26
Summary
Array
n n
Collections
n n n n
Generalization of the array concept. Set of interfaces defined in Java for storing object. Multiple types of objects. Resizable.
Use LinkedList.
27
OOP: Collections