Map : Key-Value 模型,需要根据指定 Key 找到关联的 Value。
import java.util.Map;
import java.util.TreeMap;
public class MapDemo {
public static void main(String[] args) {
Map<String, String> map = new TreeMap<>();
System.out.println(map.get("老大"));
System.out.println(map.getOrDefault("老大", "查无此人"));
String oldValue = map.put("老大", "123456");
System.out.println(oldValue);
oldValue = map.put("老大", "9999999");
System.out.println(oldValue);
map.put("老二", "1212121");
map.put("老三", "2222222");
map.put("老四", "333333");
System.out.println(map.keySet());
for (String key : map.keySet()) {
System.out.println(key);
}
System.out.println(map.values());
for (String value : map.values()) {
System.out.println(value);
}
System.out.println(map.entrySet());
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.print(entry.getKey() + " ");
System.out.println(entry.getValue());
}
System.out.println(map.containsKey("大大"));
System.out.println(map.containsKey("老大"));
System.out.println(map.containsValue("2222222"));
}
}
Set-纯 key 模型,只需要判断关键字在不在集合中即可,没有关联的 value;
Set的输出具有无序性和无重复性。
import java.util.Set;
import java.util.TreeSet;
public class SetDemo {
public static void main(String[] args) {
Set<String> bucket = new TreeSet<>();
bucket.add("苹果");
bucket.add("香蕉");
bucket.add("橘子");
bucket.add("石榴");
bucket.add("柿子");
System.out.println(bucket +" "+ bucket.size());
System.out.println(bucket.add("橘子"));
System.out.println(bucket.remove("苹果"));
System.out.println(bucket +" "+ bucket.size());
System.out.println(bucket.remove("火龙果"));
System.out.println(bucket +" "+ bucket.size());
System.out.println(bucket.contains("香蕉"));
bucket.clear();
System.out.println(bucket +" "+ bucket.size());
}
}