Intro to Collections
Array Problems (Immediate) Must know size Hard to Grow Hard to Shrink Hard to insert in middle Hard to remove from middle Manual search
Array Problems (Future) Assumes Linear Relationship Right and left neighbors
Collections Hold a group of things (like a bag) Expect that all of the things are the same kind of thing (no flour in the sugar bag) Built in: Grow Shrink Insert Remove Search Variety of data structures
Collection Problems Additional overhead Does not quite store primitives Use wrapper classes
ArrayList Do not try to use to hold "large" numbers of primatives Simplest Collection Similar to array (linear) Automatically grows, shrinks, inserts, removes, searches Sort available Do not try to use to hold "large" numbers of primatives
ArrayList Must import import java.util.ArrayList; OR
Create an ArrayList New operator creates ArrayList object ArrayList<String> names = new ArrayList<String>(); “Generic” specifies what kind of thing can go in the collection Use generic in declaration and for the new operator (types should match) New operator creates ArrayList object
Add item to ArrayList names.add(name); //adds at end names.add(i, name); //adds in middle names.add(0, name); //adds at beginning
Remove item from Array list names.remove(i); //removes ith item
Let’s you use an ArrayList like an array Get and Set an Item name = names.get(i); names.set(i, “Bruce”); Let’s you use an ArrayList like an array
boolean found = names.contain(“Bruce”); Find an Item boolean found = names.contain(“Bruce”);
ArrayList Size int numOfNames = names.size(); Size of Array List grows and shrinks automatically as items are added and removed
Print an ArrayList System.out.println(names); Handy but may not be the format you want
Sort a Collection Collections.sort(names); Note to use sort items in collection must know how to compare themselves
Wrapper Classes Danger! Each primitive (int, double, boolean, etc.) has a corresponding wrapper class int -> Integer double -> Double boolean -> Boolean Used when Java needs an object Most of the time Java will switch from primitives to wrapper objects “as needed” this is called “autoboxing”. Danger!
For Each Another kind of for loop Visits each item in a collection “in order” Can also be used with array’s for(String name : names) { System.out.println(name); }