11.4 printing of containers
Some basic types of containers
//: Holding/PrintingContainers.java // Containers print themselves automatically. import java.util.*; public class PrintContainers { static Collection fill(Collection<String> collection) { collection.add("rat"); collection.add("cat"); collection.add("dog"); collection.add("dog"); return collection; } static Map fill(Map<String,String> map) { map.put("rat", "Fuzzy"); map.put("cat", "Rags"); map.put("dog", "Bosco"); map.put("dog", "spot"); return map; } public static void main(String[] args) { System.out.println(fill(new ArrayList<String>())); System.out.println(fill(new LinkedList<String>())); System.out.println(fill(new HashSet<String>())); System.out.println(fill(new TreeSet<String>())); System.out.println(fill(new LinkedHashSet<String>())); System.out.println(fill(new HashMap<String, String>())); System.out.println(fill(new TreeMap<String, String>())); System.out.println(fill(new LinkedHashMap<String, String>())); } }/* [rat, cat, dog, dog] [rat, cat, dog, dog] [rat, cat, dog] [cat, dog, rat] [rat, cat, dog] {rat=Fuzzy, cat=Rags, dog=spot} {cat=Rags, dog=spot, rat=Fuzzy} {rat=Fuzzy, cat=Rags, dog=spot} *///~
The contents printed by collection are enclosed in square brackets, and each element is separated by commas. Map is surrounded by braces, and the key and value are linked by equal signs.
HashSet, TreeSet and LinkedHashSet are all Set types. The output is displayed in the Set. Each same item can only be saved once, but the output also shows that different sets can store elements in different ways. HashSet uses a rather complex way to store elements, as you'll learn in Chapter 17.
You don't have to specify (or consider) the size of the map, because it will automatically resize itself. Map also knows how to print itself, and it displays the associated keys and values. The storage of keys and values in the map is not their insertion order, because the HashMap implementation uses a very fast algorithm to control the order.