Java Collections API
Java Collections API
Overview
• Arrays
• Working with arrays
• Java API support for arrays
• Collection classes
• Types of collection
• Working with Collections
Java Arrays – The Basics
• Declaring an array
int[] myArray;
int[] myArray = new int[5];
String[] stringArray = new String[10];
String[] strings = new String[] {“one”, “two”};
• Maps…
String s = (String)myMap.get(“google”);
String s2 = (String)mpMap.get(“yahoo”);
Collections – Getting all items
• For Lists, we could use a for loop, and loop through the list
to get() each item
• But this doesn’t work for Maps.
• To allow generic handling of collections, Java defines an object
called an Iterator
• An object whose function is to walk through a Collection of
objects and provide access to each object in sequence
Collections – Getting all items
• Get an iterator using the iterator() method
• Iterator objects have three methods:
• next() – gets the next item in the collection
• hasNext() – tests whether it has reached the end
• remove() – removes the item just returned
• Basic iterators only go forwards
• Lists objects have a ListIterator that can go forward
and backward
Collections – Getting all items
• Simple example:
List myList = new ArrayList();
//we add items