概述
21.1 Introduction
A set is an efficient data structure for storing and processing nonduplicate elements.
A map is like a dictionary that provides a quick lookup to retrieve a value using a key.
21.2 Sets
You can create a set using one of its three concrete classes: HashSet, LinkedHashSet, or TreeSet.
- The Set interface extends the Collection interface, as shown in Figure 20.1. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements(规定Set的实例不包含重复的元素). The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is, no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.
- The AbstractSet class extends AbstractCollection and partially implements Set.
- The AbstractSet class provides concrete implementations for the equals method and the hashCode method.
- The hash code of a set is the sum of the hash codes of all the elements in the set. Since the size method and iterator method are not implemented in the AbstractSet class, AbstractSet is an abstract class.
- Three concrete classes of Set are HashSet, LinkedHashSet, and TreeSet, as shown in Figure 21.1.
21.2.1 HashSet(散列集)
The HashSet class is a concrete class that implements Set.
You can create an empty hash set using its no-arg constructor or create a hash set from an existing collection. By default, the initial capacity is 16 and the load factor is 0.75. (默认情况下,初始容量为16而客座率是0.75)If you know the size of your set, you can specify the initial capacity and load factor in the constructor. Otherwise, use the default setting. The load factor is a value between 0.0 and 1.0.
The load factor(客座率) measures how full the set is allowed to be before its capacity is increased. When the number of elements exceeds the product of the capacity and load factor(容量与客座率的乘积), the capacity is automatically doubled. For example, if the capacity is 16 and load factor is 0.75, the capacity will be doubled to 32 when the size reaches 12 (16*0.75 = 12). A higher load factor decreases the space costs but increases the search time. Generally, the default load factor 0.75 is a good tradeoff between time and space costs.
A HashSet can be used to store duplicate-free elements(存储互不相同的元素). For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code(考虑到效率因素,添加到散列集中的对象必须以一种正确分散散列码的方式来实现hashCode方法). Recall that hashCode is defined in the Object class. The hash codes of two objects must be the same if the two objects are equal. Two unequal objects may have the same hash code, but you should implement the hashCode method to avoid too many such cases. Most of the classes in the Java API implement the hashCode method. For example, the hashCode in the Integer class returns its int value. The hashCode in the Character class returns the Unicode of the character. The hashCode in the String class returns s0*31(n - 1) + s1*31(n - 2) + c + sn - 1, where si is s.charAt(i).
LISTING 21.1 TestHashSet.java
import java.util.*;
public class TestHashSet {
public static void main(String[] args) {
// Create a hash set
Set<String> set = new HashSet<>();
// Add strings to the set
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Francisco");
set.add("Beijing");
set.add("New York");
System.out.println(set);
// Display the elements in the hash set
for (String s: set) {
System.out.print(s.toUpperCase() + " ");
}
}
}
[San Francisco, New York, Paris, Beijing, London]
SAN FRANCISCO NEW YORK PARIS BEIJING LONDON
As shown in the output, the strings are not stored in the order in which they are inserted into the set. There is no particular order for the elements in a hash set. To impose an order on them, you need to use the LinkedHashSet class, which is introduced in the next section.
Since a set is an instance of Collection, all methods defined in Collection can be used for sets. Listing 21.2 gives an example that applies the methods in the Collection interface on sets.
LISTING 21.2 TestMethodsInCollection.java
public class TestMethodsInCollection {
public static void main(String[] args) {
// Create set1
java.util.Set<String> set1 = new java.util.HashSet<>();
// Add strings to set1
set1.add("London");
set1.add("Paris");
set1.add("New York");
set1.add("San Francisco");
set1.add("Beijing");
System.out.println("set1 is " + set1);
System.out.println(set1.size() + " elements in set1");
// Delete a string from set1
set1.remove("London");
System.out.println("nset1 is " + set1);
System.out.println(set1.size() + " elements in set1");
// Create set2
java.util.Set<String> set2 = new java.util.HashSet<>();
// Add strings to set2
set2.add("London");
set2.add("Shanghai");
set2.add("Paris");
System.out.println("nset2 is " + set2);
System.out.println(set2.size() + " elements in set2");
System.out.println("nIs Taipei in set2? " + set2.contains("Taipei"));
set1.addAll(set2);
System.out.println("nAfter adding set2 to set1, set1 is " + set1);
set1.removeAll(set2);
System.out.println("After removing set2 from set1, set1 is " + set1);
set1.retainAll(set2);
System.out.println("After removing common elements in set2 " + "from set1, set1 is " + set1);
}
}
set1 is [San Francisco, Beijing, New York, London, Paris]
5 elements in set1
set1 is [San Francisco, Beijing, New York, Paris]
4 elements in set1
set2 is [Shanghai, London, Paris]
3 elements in set2
Is Taipei in set2? false
After adding set2 to set1, set1 is [San Francisco, Beijing, New York, Shanghai, London, Paris]
After removing set2 from set1, set1 is [San Francisco, Beijing, New York]
After removing common elements in set2 from set1, set1 is []
21.2.2 LinkedHashSet(链式散列集)
LinkedHashSet extends HashSet with a linked-list implementation that supports an ordering of the elements in the set. The elements in a HashSet are not ordered, but the elements in a LinkedHashSet can be retrieved in the order in which they were inserted into the set. A LinkedHashSet can be created by using one of its four constructors, as shown in Figure 21.1. These constructors are similar to the constructors for HashSet.
LISTING 21.3 TestLinkedHashSet.java
import java.util.*;
public class TestLinkedHashSet {
public static void main(String[] args) {
// Create a hash set
Set<String> set = new LinkedHashSet<>();
// Add strings to the set
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Francisco");
set.add("Beijing");
set.add("New York");
System.out.println(set);
// Display the elements in the hash set
for (Object element: set)
System.out.print(element.toString().toLowerCase() + " ");
}
}
[London, Paris, New York, San Francisco, Beijing]
london paris new york san francisco beijing
Tip
If you don’t need to maintain the order in which the elements are inserted, use HashSet, which is more efficient than LinkedHashSet.
21.2.3 TreeSet(树形集)
- SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. Additionally, it provides the methods first() and last() for returning the first and last elements in the set, and headSet(toElement) and tailSet(fromElement) for returning a portion of the set whose elements are less than toElement and greater than or equal to fromElement, respectively.
- NavigableSet extends SortedSet to provide navigation methods lower(e), floor(e), ceiling(e), and higher(e) that return elements respectively less than, less than or equal, greater than or equal, and greater than a given element and return null if there is no such element. The pollFirst() and pollLast() methods remove and return the first and last element in the tree set, respectively.
- TreeSet implements the SortedSet interface. To create a TreeSet, use a constructor, as shown in Figure 21.1. You can add objects into a tree set as long as they can be compared with each other.
- As discussed in Section 20.5, the elements can be compared in two ways: using the Comparable interface or the Comparator interface.
LISTING 21.4 TestTreeSet.java
import java.util.*;
public class TestTreeSet {
public static void main(String[] args) {
// Create a hash set
Set<String> set = new HashSet<>();
// Add strings to the set
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Francisco");
set.add("Beijing");
set.add("New York");
TreeSet<String> treeSet = new TreeSet<>(set);
System.out.println("Sorted tree set: " + treeSet);
// Use the methods in SortedSet interface
System.out.println("first(): " + treeSet.first());
System.out.println("last(): " + treeSet.last());
System.out.println("headSet("New York"): " + treeSet.headSet("New York"));
System.out.println("tailSet("New York"): " + treeSet.tailSet("New York"));
// Use the methods in NavigableSet interface
System.out.println("lower("P"): " + treeSet.lower("P"));
System.out.println("higher("P"): " + treeSet.higher("P"));
System.out.println("floor("P"): " + treeSet.floor("P"));
System.out.println("ceiling("P"): " + treeSet.ceiling("P"));
System.out.println("pollFirst(): " + treeSet.pollFirst());
System.out.println("pollLast(): " + treeSet.pollLast());
System.out.println("New tree set: " + treeSet);
}
}
Sorted tree set: [Beijing, London, New York, Paris, San Francisco]
first(): Beijing
last(): San Francisco
headSet("New York"): [Beijing, London]
tailSet("New York"): [New York, Paris, San Francisco]
lower("P"): New York
higher("P"): Paris
floor("P"): New York
ceiling("P"): Paris
pollFirst(): Beijing
pollLast(): San Francisco
New tree set: [London, New York, Paris]
The elements in the set are sorted once you create a TreeSet object from a HashSet object using new TreeSet<String>(set) (line 16). You may rewrite the program to create an instance of TreeSet using its no-arg constructor, and add the strings into the TreeSet object.
- u treeSet.first() returns the first element in treeSet.
- u treeSet.last() returns the last element in treeSet.
- u treeSet.headSet("New York") returns the elements in treeSet before New York.
- u treeSet.tailSet("New York") returns the elements in treeSet after New York, including New York.
- u treeSet.lower("P") returns the largest element less than P in treeSet.
- u treeSet.higher("P") returns the smallest element greater than P in treeSet.
- u treeSet.floor("P") returns the largest element less than or equal to P in treeSet.
- u treeSet.ceiling("P") returns the smallest element greater than or equal to P in treeSet.
- u treeSet.pollFirst() removes the first element in treeSet and returns the removed element.
- u treeSet.pollLast() removes the last element in treeSet and returns the removed element.
Note
All the concrete classes in Java Collections Framework (see Figure 20.1) have at least two constructors. One is the no-arg constructor that constructs an empty collection. The other constructs instances from a collection. Thus the TreeSet class has the constructor TreeSet(Collection c) for constructing a TreeSet from a collection c. In this example, new TreeSet<>(set) creates an instance of TreeSet from the collection set.
Tip
If you don’t need to maintain a sorted set when updating a set, you should use a hash set, because it takes less time to insert and remove elements in a hash set. When you need a sorted set, you can create a tree set from the hash set.
If you create a TreeSet using its no-arg constructor, the compareTo method is used to compare the elements in the set, assuming that the class of the elements implements the Comparable interface. To use a comparator, you have to use the constructor TreeSet(Comparator comparator) to create a sorted set that uses the compare method in the comparator to order the elements in the set.
LISTING 21.5 TestTreeSetWithComparator.java
import java.util.*;
public class TestTreeSetWithComparator {
public static void main(String[] args) {
// Create a tree set for geometric objects using a comparator
Set<GeometricObject> set = new TreeSet<>(new GeometricObjectComparator());
set.add(new Rectangle(4, 5));
set.add(new Circle(40));
set.add(new Circle(40));
set.add(new Rectangle(4, 1));
// Display geometric objects in the tree set
System.out.println("A sorted set of geometric objects");
for (GeometricObject element: set)
System.out.println("area = " + element.getArea());
}
}
A sorted set of geometric objects
area = 4.0
area = 20.0
area = 5021.548245743669
The GeometricObjectComparator class is defined in Listing 20.4.
The Circle and Rectangle classes were defined in Section 13.2, Abstract Classes.
21.3 Comparing the Performance of Sets and Lists
Sets are more efficient than lists for storing nonduplicate elements. Lists are useful for accessing elements through the index.
The elements in a list can be accessed through the index. However, sets do not support indexing, because the elements in a set are unordered. To traverse all elements in a set, use a foreach loop.
LISTING 21.6 SetListPerformanceTest.java
import java.util.*;
public class SetListPerformanceTest {
static final int N = 50000;
public static void main(String[] args) {
// Add numbers 0, 1, 2, ..., N - 1 to the array list
List<Integer> list = new ArrayList<>();
for (int i = 0; i < N; i++)
list.add(i);
Collections.shuffle(list); // Shuffle the array list
// Create a hash set, and test its performance
Collection<Integer> set1 = new HashSet<>(list);
System.out.println("Member test time for hash set is " +
getTestTime(set1) + " milliseconds");
System.out.println("Remove element time for hash set is " +
getRemoveTime(set1) + " milliseconds");
// Create a linked hash set, and test its performance
Collection<Integer> set2 = new LinkedHashSet<>(list);
System.out.println("Member test time for linked hash set is " +
getTestTime(set2) + " milliseconds");
System.out.println("Remove element time for linked hash set is "
+ getRemoveTime(set2) + " milliseconds");
// Create a tree set, and test its performance
Collection<Integer> set3 = new TreeSet<>(list);
System.out.println("Member test time for tree set is " +
getTestTime(set3) + " milliseconds");
System.out.println("Remove element time for tree set is " +
getRemoveTime(set3) + " milliseconds");
// Create an array list, and test its performance
Collection<Integer> list1 = new ArrayList<>(list);
System.out.println("Member test time for array list is " +
getTestTime(list1) + " milliseconds");
System.out.println("Remove element time for array list is " +
getRemoveTime(list1) + " milliseconds");
// Create a linked list, and test its performance
Collection<Integer> list2 = new LinkedList<>(list);
System.out.println("Member test time for linked list is " +
getTestTime(list2) + " milliseconds");
System.out.println("Remove element time for linked list is " +
getRemoveTime(list2) + " milliseconds");
}
public static long getTestTime(Collection<Integer> c) {
long startTime = System.currentTimeMillis();
// Test if a number is in the collection
for (int i = 0; i < N; i++)
c.contains((int)(Math.random() * 2 * N));
return System.currentTimeMillis() - startTime;
}
public static long getRemoveTime(Collection<Integer> c) {
long startTime = System.currentTimeMillis();
for (int i = 0; i < N; i++)
c.remove(i);
return System.currentTimeMillis() - startTime;
}
}
Member test time for hash set is 13 milliseconds
Remove element time for hash set is 8 milliseconds
Member test time for linked hash set is 10 milliseconds
Remove element time for linked hash set is 10 milliseconds
Member test time for tree set is 22 milliseconds
Remove element time for tree set is 20 milliseconds
21.4 Case Study: Counting Keywords
For each word in a Java source file, we need to determine whether the word is a keyword. To handle this efficiently, store all the keywords in a HashSet and use the contains method to test if a word is in the keyword set. Listing 21.7 gives this program.
LISTING 21.7 CountKeywords.java
import java.util.*;
import java.io.*;
public class CountKeywords {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Java source file: ");
String filename = input.nextLine();
File file = new File(filename);
if (file.exists()) {
System.out.println("The number of keywords in " + filename
+ " is " + countKeywords(file));
}
else {
System.out.println("File " + filename + " does not exist");
}
}
public static int countKeywords(File file) throws Exception {
// Array of all Java keywords + true, false and null
String[] keywordString = {"abstract", "assert", "boolean",
"break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else", "enum",
"extends", "for", "final", "finally", "float", "goto",
"if", "implements", "import", "instanceof", "int",
"interface", "long", "native", "new", "package", "private",
"protected", "public", "return", "short", "static",
"strictfp", "super", "switch", "synchronized", "this",
"throw", "throws", "transient", "try", "void", "volatile",
"while", "true", "false", "null"};
Set<String> keywordSet = new HashSet<>(Arrays.asList(keywordString));
int count = 0;
Scanner input = new Scanner(file);
while (input.hasNext()) {
String word = input.next();
if (keywordSet.contains(word))
count++;
}
return count;
}
}
21.5 Maps
You can create a map using one of its three concrete classes: HashMap, LinkedHashMap, or TreeMap.
A map is a container object that stores a collection of key/value pairs. It enables fast retrieval, deletion, and updating of the pair through the key. A map stores the values along with the keys. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding value form an entry stored in a map, as shown in Figure 21.2a. Figure 21.2b shows a map in which each entry consists of a Social Security number as the key and a name as the value.
There are three types of maps: HashMap, LinkedHashMap, and TreeMap. The common features of these maps are defined in the Map interface. Their relationship is shown in Figure 21.3.
The Map interface provides the methods for querying, updating, and obtaining a collection of values and a set of keys, as shown in Figure 21.4.
The update methods include clear, put, putAll, and remove.
- The clear() method removes all entries from the map.
- The put(K key, V value) method adds an entry for the specified key and value in the map. If the map formerly contained an entry for this key, the old value is replaced by the new value and the old value associated with the key is returned.
- The putAll(Map m) method adds all entries in m to this map.
- The remove(Object key) method removes the entry for the specified key from the map.
The query methods include containsKey, containsValue, isEmpty, and size.
- The containsKey(Object key) method checks whether the map contains an entry for the specified key.
- The containsValue(Object value) method checks whether the map contains an entry for this value.
- The isEmpty() method checks whether the map contains any entries.
- The size() method returns the number of entries in the map.
You can obtain a set of the keys in the map using the keySet() method, and a collection of the values in the map using the values() method. The entrySet() method returns a set of entries. The entries are instances of the Map.Entry<K, V> interface, where Entry is an inner interface for the Map interface, as shown in Figure 21.5. Each entry in the set is a key/value pair in the underlying map.
The AbstractMap class is a convenience abstract class that implements all the methods in the Map interface except the entrySet() method. The HashMap, LinkedHashMap, and TreeMap classes are three concrete implementations of the Map interface, as shown in Figure 21.6.
The HashMap class is efficient for locating a value, inserting an entry, and deleting an entry.
LinkedHashMap extends HashMap with a linked-list implementation that supports an ordering of the entries in the map. The entries in a HashMap are not ordered, but the entries in a LinkedHashMap can be retrieved either in the order in which they were inserted into the map (known as the insertion order) or in the order in which they were last accessed, from least recently to most recently accessed (access order). The no-arg constructor constructs a LinkedHashMap with the insertion order.
To construct a LinkedHashMap with the access order, use LinkedHashMap(initialCapacity, loadFactor, true).
The TreeMap class is efficient for traversing the keys in a sorted order. The keys can be sorted using the Comparable interface or the Comparator interface. If you create a TreeMap using its no-arg constructor, the compareTo method in the Comparable interface is used to compare the keys in the map, assuming that the class for the keys implements the Comparable interface.
To use a comparator, you have to use the TreeMap(Comparator comparator) constructor to create a sorted map that uses the compare method in the comparator to order the entries in the map based on the keys.
SortedMap is a subinterface of Map, which guarantees that the entries in the map are sorted. Additionally, it provides the methods firstKey() and lastKey() for returning the first and last keys in the map, and headMap(toKey) and tailMap(fromKey) for returning a portion of the map whose keys are less than toKey and greater than or equal to fromKey, respectively.
NavigableMap extends SortedMap to provide the navigation methods lowerKey(key), floorKey(key), ceilingKey(key), and higherKey(key) that return keys respectively less than, less than or equal, greater than or equal, and greater than a given key and return null if there is no such key. The pollFirstEntry() and pollLastEntry() methods remove and return the first and last entry in the tree map, respectively.
Note
Prior to Java 2, java.util.Hashtable was used for mapping keys with values. Hashtable was redesigned to fit into the Java Collections Framework with all its methods retained for compatibility. Hashtable implements the Map interface and is used in the same way as HashMap, except that the update methods in Hashtable are synchronized.
LISTING 21.8 TestMap.java
import java.util.*;
public class TestMap {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Smith", 30);
hashMap.put("Anderson", 31);
hashMap.put("Lewis", 29);
hashMap.put("Cook", 29);
System.out.println("Display entries in HashMap");
System.out.println(hashMap + "n");
// Create a TreeMap from the preceding HashMap
Map<String, Integer> treeMap = new TreeMap<>(hashMap);
System.out.println("Display entries in ascending order of key");
System.out.println(treeMap);
// Create a LinkedHashMap
Map<String, Integer> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true);
linkedHashMap.put("Smith", 30);
linkedHashMap.put("Anderson", 31);
linkedHashMap.put("Lewis", 29);
linkedHashMap.put("Cook", 29);
// Display the age for Lewis
System.out.println("nThe age for " + "Lewis is " + linkedHashMap.get("Lewis"));
System.out.println("Display entries in LinkedHashMap");
System.out.println(linkedHashMap);
}
}
Display entries in HashMap
{Lewis=29, Smith=30, Cook=29, Anderson=31}
Display entries in ascending order of key
{Anderson=31, Cook=29, Lewis=29, Smith=30}
The age for Lewis is 29
Display entries in LinkedHashMap
{Smith=30, Anderson=31, Cook=29, Lewis=29}
As shown in the output, the entries in the HashMap are in random order. The entries in the TreeMap are in increasing order of the keys. The entries in the LinkedHashMap are in the order of their access, from least recently accessed to most recently.
All the concrete classes that implement the Map interface have at least two constructors. One is the no-arg constructor that constructs an empty map, and the other constructs a map from an instance of Map.
Tip
If you don’t need to maintain an order in a map when updating it, use a HashMap. When you need to maintain the insertion order or access order in the map, use a LinkedHashMap. When you need the map to be sorted on keys, use a TreeMap.
21.6 Case Study: Occurrences of Words
This case study writes a program that counts the occurrences of words in a text and displays the words and their occurrences in alphabetical order of the words.
The program uses a TreeMap to store an entry consisting of a word and its count. For each word, check whether it is already a key in the map. If not, add an entry to the map with the word as the key and value 1. Otherwise, increase the value for the word (key) by 1 in the map. Assume the words are case insensitive; e.g., Good is treated the same as good.
LISTING 21.9 CountOccurrenceOfWords.java
import java.util.*;
public class CountOccurrenceOfWords {
public static void main(String[] args) {
// Set text in a string
String text = "Good morning. Have a good class. " +
"Have a good visit. Have fun!";
// Create a TreeMap to hold words as key and count as value
Map<String, Integer> map = new TreeMap<>();
String[] words = text.split("[ ntr.,;:!?(){");
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase();
if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
}
else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}
// Get all entries into a set
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
// Get key and value from each entry
for (Map.Entry<String, Integer> entry: entrySet)
System.out.println(entry.getValue() + "t" + entry.getKey());
}
}
a 2
class 1
fun 1
good 3
have 3
morning 1
visit 1
21.7 Singleton and Unmodifiable Collections and Maps
You can create singleton sets, lists, and maps and unmodifiable sets, lists, and maps using the static methods in the Collections class.
The Collections class contains the static methods for lists and collections. It also contains the methods for creating immutable singleton sets, lists, and maps, and for creating read-only sets, lists, and maps, as shown in Figure 21.7.
The Collections class defines three constants—EMPTY_SET, EMPTY_LIST, and EMPTY_MAP—for an empty set, an empty list, and an empty map. These collections are immutable. The class also provides the singleton(Object o) method for creating an immutable set containing only a single item, the singletonList(Object o) method for creating an immutable list containing only a single item, and the singletonMap(Object key, Object value) method for creating an immutable map containing only a single entry.
The Collections class also provides six static methods for returning read-only views for collections: unmodifiableCollection(Collection c), unmodifiableList(List list), unmodifiableMap(Map m), unmodifiableSet(Set set), unmodifiableSortedMap(SortedMap m), and unmodifiableSortedSet(Sorted Set s). This type of view is like a reference to the actual collection. But you cannot modify the collection through a read-only view. Attempting to modify a collection through a readonly view will cause an UnsupportedOperationException.
CHAPTER 21 SUMMARY
1. A set stores nonduplicate elements. To allow duplicate elements to be stored in a collection, you need to use a list.
2. A map stores key/value pairs. It provides a quick lookup for a value using a key.
3. Three types of sets are supported: HashSet, LinkedHashSet, and TreeSet. HashSet stores elements in an unpredictable order. LinkedHashSet stores elements in the order they were inserted. TreeSet stores elements sorted. All the methods in HashSet, LinkedHashSet, and TreeSet are inherited from the Collection interface.
4. The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key can map to at most one value. The Map interface provides the methods for querying, updating, and obtaining a collection of values and a set of keys.
5. Three types of maps are supported: HashMap, LinkedHashMap, and TreeMap. HashMap is efficient for locating a value, inserting an entry, and deleting an entry. LinkedHashMap supports ordering of the entries in the map. The entries in a Hash- Map are not ordered, but the entries in a LinkedHashMap can be retrieved either in the order in which they were inserted into the map (known as the insertion order) or in the order in which they were last accessed, from least recently accessed to most recently (access order). TreeMap is efficient for traversing the keys in a sorted order. The keys can be sorted using the Comparable interface or the Comparator interface.
最后
以上就是直率高山为你收集整理的Java学习笔记(21) sets and maps21.1 Introduction21.2 Sets21.3 Comparing the Performance of Sets and Lists21.4 Case Study: Counting Keywords21.5 Maps21.6 Case Study: Occurrences of Words21.7 Singleton and Unmodifiable Collections and MapsCHAPTER 21 SUMMARY的全部内容,希望文章能够帮你解决Java学习笔记(21) sets and maps21.1 Introduction21.2 Sets21.3 Comparing the Performance of Sets and Lists21.4 Case Study: Counting Keywords21.5 Maps21.6 Case Study: Occurrences of Words21.7 Singleton and Unmodifiable Collections and MapsCHAPTER 21 SUMMARY所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复