Collections

Collection

Some CIS 22 Review (hopefully) Material

A Hierarchy of Collections

Collection

List Set Map SortedSet SortedMap Iterator Vector
Vector v = new Vector();
String line = br.readLine(); // assume BufferedReader br
while (line != null) {
	v.add(line);					// could add ANY object to v
	line = br.readLine();
}
		
Iterator iter = v.iterator();
while (iter.hasNext()) {
	String s = (String)iter.next();		// Have to state that it's a String
	System.err.println(s);					//  or do whatever you want with the string
}
	

Stack

Queue HashSet
HashSet hs = new HashSet();
String line = br.readLine(); // assume BufferedReader br
while (line != null) {
	hs.add(line);					// could add ANY object to hs
	line = br.readLine();
}
		
Iterator iter = hs.iterator();			
while (iter.hasNext()) {					// No particular order
	String s = (String)iter.next();		// Have to state that it's a String
	System.err.println(s);					//  or do whatever you want with the string
}
	

HashMap

HashMap hm = new HashMap();
Employee employee = Employee.read(br); // assume BufferedReader br
while (employee != null) {
	hm.put(employee.getSSNum(), employee));	// could use ANY key or value for tm
	employee = Employee.read(br);
}
		
Set keys = hm.keySet();						// Get the set of keys
Iterator iter = keys.iterator();			
while (iter.hasNext()) {					// No particular order
	String sSNum = (String)iter.next();	// Have to state that it's a String
	Employee e = (Employee)tm.get(sSNum);		
	System.err.println(e);					//  or do whatever you want with the Employee object
}
	

  • TreeSet
    TreeSet ts = new TreeSet();
    String line = br.readLine(); // assume BufferedReader br
    while (line != null) {
    	ts.add(line);					// could add ANY object to ts
    	line = br.readLine();
    }
    		
    Iterator iter = ts.iterator();			
    while (iter.hasNext()) {					// Natural order of String (alphabetical order)
    	String s = (String)iter.next();		// Have to state that it's a String
    	System.err.println(s);					//  or do whatever you want with the string
    }
    	

    TreeMap

    TreeMap tm = new TreeMap();
    Employee employee = Employee.read(br); // assume BufferedReader br
    while (employee != null) {
    	tm.put(employee.getSSNum, employee));	// could use ANY key or value for tm
    	line = br.readLine();
    }
    
    Set keys = tm.keySet();						// Get the set of keys
    Iterator iter = keys.iterator();			
    while (iter.hasNext()) {					// Natural order of the key -- a String (alphabetical order)
    	String sSNum = (String)iter.next();	// Have to state that it's a String
    	Employee e = (Employee)tm.get(sSNum);		
    	System.err.println(e);					//  or do whatever you want with the Employee object
    }
    	

    LinkedList

    Deque (not implemented in Java)