HashMap
Map中不允许有重复的键
Map接口有2个实现,分为
HashMap和TreeMap
TreeMap保存了数据的排列次序,HashMap不能。
HashMap本身是非线程安全的,但是collection框架提供方法可以保证HashMap是线程安全的。
put(key,value)添加键值对
HashSet
不允许集合中有重复值
add(Object o)添加对象
测试代码
public class Test {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
map.put(5, "e");
HashMap<Integer, String> hmap = new HashMap<>();
hmap.put(11, "aa");
hmap.put(22, "bb");
hmap.put(33, "cc");
hmap.put(44, "dd");
hmap.put(55, "ee");
Set<String> set = new HashSet<>();
set.add("1");
set.add("2");
set.add("3");
set.add("3");
//遍历treeMap
for (Map.Entry<Integer, String> tm : map.entrySet()) {
System.out.println(tm.getKey() + "---" + tm.getValue());
}
//遍历hashMap
for (Map.Entry<Integer, String> hm : hmap.entrySet()) {
System.out.println(hm.getKey() + "---" + hm.getValue());
}
System.out.println(set);
//迭代器
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
//一次循环中iterator.next()方法不能出现两次,否则会报NoSuchElementException异常
String next = iterator.next();
if ("1".equals(next)) {
System.out.println("找到了");
}
}
}
}
控制台输出