import java.util.*;
public class SetAndMap {
public static void main(String[] args) {
System.out.println("---------Set部分-----------");
HashSet<Integer> S = new HashSet<Integer>();
S.add(8);
S.add(1);
S.add(7);
S.add(4);
S.add(8);
S.add(4);
printSet(S);
S.remove(7);
printSet(S);
S.add(2);
printSet(S);
if(S.contains(10) == false) System.out.println("not found.");
System.out.println("\n---------Map部分-----------");
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("red", 32);
map.put("blue", 688);
map.put("yello", 122);
map.put("blue", map.get("blue") + 312);
printMap(map);
map.put("zebra", 101010);
map.put("white", 0);
map.remove("yello");
printMap(map);
}
public static void printSet(HashSet/*也可以使用Set*/ set){
Iterator<Integer> it = set.iterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
System.out.println();
}
public static void printMap(HashMap<String, Integer>/*也可以使用Set*/ map){
Set<String> key_set = map.keySet();
System.out.println(map.size());
Iterator<String> it = key_set.iterator();
while(it.hasNext()){
String key = it.next();
int value = map.get(key);
System.out.print(key + " --> " + value);
System.out.println();
}
System.out.println();
}
}
输出:
---------Set部分-----------
1 4 7 8
1 4 8
1 2 4 8
not found.
---------Map部分-----------
3
red --> 32
blue --> 1000
yello --> 122
4
red --> 32
zebra --> 101010
blue --> 1000
white --> 0