You are on page 1of 7

8/18/2009

Java Collections Framework

Object Oriented Programming

Colecciones

The Java Collection API


• General features
• Generics and parameterization
• Overriding equals() and hashCode()
• Enumerations
• Defining generic abstract types
• For each control structure
For-each
• Autoboxing

1
8/18/2009

Collections Framework General-Purpose Implementation


classes
• Collection The primary implementations of the collection interfaces.
– Generic container, most of the framework implements this
• HashSet : Hash table implementation of the Set interface.
• List • TreeSet : Red-black tree implementation of the SortedSet interface.
– stores multiple items in an explicit order (repeated elements allowed) • ArrayList : Resizable-array implementation of the List interface.
– ArrayList, LinkedList, etc. – (Essentially an unsynchronized Vector.) The best all-around
• Set implementation of the List interface.
– stores unique items in no particular order • LinkedList : Doubly-linked list implementation of the List interface.
– HashSet, SortedSet, etc. – May provide better performance than the ArrayList implementation if
elements are frequently inserted or deleted within the list.
• Map – Useful for queues and double-ended queues (deques).
– stores unordered key-value pairs (like a dictionary; keys are unique)
• HashMap : Hash table implementation of the Map interface.
– HashMap, Hastable, TreeMap, etc.
– (Essentially an unsynchronized Hashtable that supports null keys and
Buena práctica: values.) The best all-around implementation of the Map interface.
– No exponer tipos de datos usados innecesariamente • TreeMap : Red-black tree implementation of the SortedMap interface.
• E.g., declare Map, instancie un HashMap()

Collection Operation Generic Types


• Collections typically provide these operations: • Antes de Java 5, se podía recorrer una lista como
– add(Object o) – add an object to the collection sigue:
– remove(Object o) – remove the object public String concat(ArrayList list) {
– clear() – remove all objects from collection int i;
StringBuffer buff = new StringBuffer();
– size()
() – returns a count of objects
j in collection
for (i = 0; i< list.size(); i++) {
– isEmpty() – returns true if collection is empty
String element = (String) lista.get(i);
– iterator() – traverse contents of collection
buff.append(element);
– contains(Object element); // use equals() for comparison }
return buff.toString();
}

• Some operations are optional • Qué problema hay? ……. Casting?


• Some operations are slower/faster

2
8/18/2009

Generic Types Arraylist, Generics


• A partir de Java 5 • Crear un ArrayList usando Generics:
• public String concat(List<String> list) { – ArrayList<Integer> listA = new ArrayList<Integer>();
StringBuffer buff = new StringBuffer();
for (String element : list) { • Añadir elementos al ArrayList
buff.append(element);
pp – listA
listA.add(new
add(new Integer(i));
} – listA.add(new Integer(i+1));
return buff.toString();
• } – O
– listA.add(1); //Gracias a Autoboxing
• Es código más corto y garantiza que el tipo de datos de la lista es
String, además no requiere casting

Arraylist in a program Arraylist in a program

• Buscar por un Object y retornar su posición • Check to see if the List is empty:

int locationIndex = listA.indexOf("Jeff");


( ); System.out.println("Is List A empty?
" + li
listA.isEmpty());
tA i E t ())

3
8/18/2009

The Set Interface Set - API


• Is a Collection that cannot contain duplicate • Almost everything has been done for you
elements. • Union of two sets – Use:
– boolean addAll(Collection c)
• Models the mathematical set abstraction. • Intersection of two sets – Use:
– boolean
b l retainAll(Collection
t i All(C ll ti c))

• Two Set objects are equal if they contain the same • Difference of two sets (A – B) – Use:
elements. • boolean removeAll(Collection c)

• Two direct implementations:


– HashSet TreeSet

The Set Interface Practica


• Contains no methods other than those inherited from
Collection.
• Dado un arreglo de Strings, añada todos los
– Same signatures but different semantics ( meaning ) elementos a un Set e imprima los duplicados a
medida que los va añadiendo
– Collection c = new LinkedList();
– Set s = new HashSet();
– String o = “a”; • String[] palabras={“Hay”, “una””, “una” , “pal”}
– c.add(o); c.add(o) ; // both return true; c.size() == 2
Set s = new HashSet();
– s.add(o); s.add(o) ; // 2nd add() returns false; s.size() == 1

• It adds the restriction that duplicate elements are prohibited.


– Collection noDups = new HashSet(c); // a simple way to eliminate
duplicate from c

4
8/18/2009

Iterator (alternatative way) Using Both ArrayList and Sets

• // you must create iterator for set • You may want to use a set to get rid of duplicates,
• Iterator<String> iter2 = firstnames.iterator(); then put the items in an ArrayList and sort them!
• // use iterator to print elements in set • Problem:
– Often data comes in the form of an array
• while (iter2.hasNext())
– How
o do we e go from
o array
a ay to ArrayList
ay st oor TreeSet?
eeSet
• { • Problem:
• System.out.println(iter2.next()); – Often we are required to return an array
• } – How do we go from a Collection such as an ArrayList or TreeSet to
an array?
• Can do it the “hard” way with loops or iterators:
• OR:

Converting from array to Collection Converting from Collection to array

• For arrays of objects (such as Strings) use the asList • Collections such as ArrayLists and TreeSets have a
method in the Arrays class. toArray method
• This returns a fixed-size list backed by the specified – This returns an array
array – Sintax: a bit awkward
• Pass this into the constructor of your ArrayList or set • Example
• TreeSet<String> wordset = new TreeSet<String>();
• Example
• . . .
• String[] words = String[N];
• String[] words =
• . . . • (String[]) wordset.toArray(new String[0]);
• TreeSet<String> wordset = new • or
• TreeSet<String>(Arrays.asList(words)); • return (String[]) wordset.toArray(new String[0]);

5
8/18/2009

The Map interface Map


// Bulk Operations
void putAll(Map t); //optional
• Keys map to values
void clear(); // optional
// Collection Views;
// backed by the Map, change on either will be reflected on the other. • Map<String, String> m = new TreeMap<String, String>();
public Set keySet(); // cannot duplicate by definition!!
public Collection values(); // can duplicate
public Set entrySet(); // no equivalent in Dictionary
// nested Interface for entrySet elements
public interface Entry {
Object getKey();
Object getValue();
Object setValue(Object value); }}

Basic Operations Map example

• Map m = new HashMap(); public class Birthday {


public static void main(String[] args){
Map<String, Integer> m =
................ new HashMap<String, Integer>();
m.put("Newton", new Integer(1642));
• Put in a key
y and its value p ( , new Integer(1809));
m.put("Darwin", g ( ));
System.out.println(m);
• m.put(”Forbes”, ”Strawberry”); }
• Get a value for a key }

• val = m.get(”Forbes”); Output:


{Darwin=1809, Newton=1642}
• Change value for key
• m.put(”Forbes”, ”Coffee Mocha”);
35

6
8/18/2009

Map Iterator Example


public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<String, Integer>( );
map.put( "One", 1);
map.put("Two", 2);
map.put( "Three",3);

// get the set of keys and an iterator


Set<String> keys = map.keySet( );
Iterator<String>
It t <St i > ititer = k
keys.iterator(
it t ( ));

// sequence through the keys and get the values


while (iter.hasNext()){
String key = iter.next();
System.out.println(key + ", " + map.get(key));
}
}
// --- Output --
Three, 3
One, 1
Two, 2

Iterator HashSet vs treeSet (and HashMap vs


TreeMap)
public static void printHashMap(HashMap hashMap) { • HashSet/ HashMap is much faster (constant time vs. log
System.out.print( "HashMap: " ); time for most operations), but offers no ordering
guarantees.
Iterator iterator = hashMap.entrySet().iterator();
• always use HashSet/HashMap unless you need to use
while (iterator.hasNext())
(iterator hasNext()) { the operations in the SortedSet,
SortedSet or in-order
in order iteration
iteration.
Map.Entry entry = (Map.Entry) iterator.next(); • choose an appropriate initial capacity of your HashSet if
System.out.print( "(" + entry.getKey() + ": " + iteration performance is important.
entry.getValue() + "), " );
– The default initial capacity is 101, and that's often more than you
}
need.
System.out.println();
– can be specified using the int constructor.
}
– Set s= new HashSet(17); // set bucket size to 17

You might also like