Java Reference
In-Depth Information
class CollectionsTester {
public static void main(String[] args) {
ArrayList<String> listOfStrings = new ArrayList<String>();
listOfStrings.add("first item");
listOfStrings.add("second item");
listOfStrings.add("third item");
listOfStrings.add("fourth item");
listOfStrings.remove(0); // Remove the first item
HashSet<Integer> setOfIntegers = new HashSet<Integer>();
setOfIntegers.add(2);
setOfIntegers.add(4);
setOfIntegers.add(2);
setOfIntegers.remove(2);
HashMap<String,Integer> mapOfStringToInteger =
new HashMap<String,Integer>();
mapOfStringToInteger.put("Alice", 4);
mapOfStringToInteger.put("Bob", 3);
mapOfStringToInteger.remove("Alice");
}
}
3.
Eclipse will complain about the fact that it does not recognize the ArrayList , HashSet , and
HashMap classes. If you mouse over the error, you will see that Eclipse automatically provides a
way to import these classes. The first option is Import 'ArrayList' (java.util) .
4.
Another handy way to automatically resolve missing imports in Eclipse is by navigating to Source
and then selecting Organize Imports. You can also use the helpful keyboard shortcut Ctrl+Shift+O.
After fixing all the errors, the following imports should appear at the beginning of your code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
How It Works
Now take a look at how it works.
1.
The CollectionsTester class shows the use of ArrayList , HashSet , and HashMap classes, that is,
lists, sets, and maps. These are the three collection types you'll use the most.
2.
The program returns no output, but you can use the get() method to retrieve and show items
from the collections. Take some time to play around with this code fragment to get a feel for the
different methods provided by the collection types. You can use Eclipse's context menu to browse
around by typing listOfStrings and then looking through the possible methods offered.
You will be using collection types extensively throughout the remainder of this topic, and you will
become more familiar with them as you move on. For now, I leave you with two remarks. First, note
that most collection types (sets and lists) in Java implement the Collection interface. You have not
Search WWH ::




Custom Search