1. Java: TreeMap HashMap C++ : map unordered_map
//结论:与c++不一样 [经过验证] // java 相同Key值时,使用新的Value // c++ 相同Key值时,使用旧的Value
private void testTreeMapOrder3() { TreeMap<Student, String> treeMap = new TreeMap<>(); treeMap.put(new Student(25, "name1"), "test1"); treeMap.put(new Student(26, "name3"), "same0"); treeMap.put(new Student(26, "name3"), "same1"); treeMap.put(new Student(27, "name4"), "test4"); for (Iterator itr = treeMap.entrySet().iterator(); itr.hasNext(); ) { Map.Entry entry = (Map.Entry) itr.next(); Student key = (Student) entry.getKey(); String value = (String) entry.getValue(); System.out.println(String.format("key:%s value:%s", key, value)); } // 是否在与自己比较:true 相同:age:25 name:name1 //原因:源码中,插入第一个元素时,compare(key, key); // 是否在与自己比较:false 相同:age:26 name:name3 // key:age:25 name:name1 value:test1 // key:age:26 name:name3 value:same1 // key:age:27 name:name4 value:test4 //分析源代码 // if (cmp < 0) // t = t.left; // else if (cmp > 0) // t = t.right; // else // return t.setValue(value); //更换为最新的值 //结论:与c++不一样 [经过验证] // java 相同Key值时,使用新的Value // c++ 相同Key值时,使用旧的Value }
2. TreeMap的遍历(HashMap遍历一样)
for (Iterator itr = treeMap.entrySet().iterator(); itr.hasNext(); ) {
Map.Entry entry = (Map.Entry) itr.next();
Student key = (Student) entry.getKey();
String value = (String) entry.getValue();
System.out.println(String.format("key:%s value:%s", key, value));
}
3.hashSet遍历 (在遍历时同时删除:一定要使用迭代器 itr.remove())
for (Iterator<Student> itr = hashSet.iterator(); itr.hasNext(); ) {
Student student = itr.next();
System.out.println("student:" + student);
if (student.mAge == 2)
itr.remove();
}
for (Student student : hashSet) {
System.out.println("student:" + student);
}
4.new ArrayList<>(otherList) 采用浅复制
private static void testClone4() {
List<People> peopleList1 = new ArrayList<>();
peopleList1.add(new People(1, "ye huang"));
peopleList1.add(new People(2, "wang yi"));
peopleList1.add(new People(3, "zhang yue"));
System.out.println("peopleList1:" + peopleList1);
List<People> peopleList2 = new ArrayList<>(peopleList1);
for (People people : peopleList2) {
people.age = 66;
people.name = "maintop";
}
System.out.println("peopleList1:" + peopleList1);
System.out.println("peopleList2:" + peopleList2);
// 对象个数:1
// 对象个数:2
// 对象个数:3
// peopleList1:[age:1 name:ye huang, age:2 name:wang yi, age:3 name:zhang yue]
// peopleList1:[age:66 name:maintop, age:66 name:maintop, age:66 name:maintop]
// peopleList2:[age:66 name:maintop, age:66 name:maintop, age:66 name:maintop]
//浅复制
}
不过String的行为不一样
private static void testClone() { List<String> list1 = new ArrayList<>(); list1.add("A"); list1.add("B"); list1.add("C"); List<String> list2 = new ArrayList<>(list1); list2.set(0, "I"); System.out.println("list1:" + list1); System.out.println("list2:" + list2); // list1:[A, B, C] // list2:[I, B, C] //结论: [可能是String的缘故] [我猜测可能与Qt中String类似,当被修改后,才会再创建一个对象] }