更新时间:2022-09-21 19:11:08
测试用例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package test;
import org.junit.Test;
import po.Person;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
/** * Created by Administrator on 2015/9/16.
*/
public class TestMap {
/**
* map插入相同key问题,value会不会覆盖
*/
@Test
public void testMap(){
//HashMap中key的内容相同,则覆盖
Map<String,Object> map1 = new HashMap<>();
map1.put( "张三" , 1 );
map1.put( "张三" , 2 );
map1.put( new String( "张三" ), 3 ); //根据String特性,这三条内容相同,前两条地址相同
map1.put( "李四" , 4 );
for (String s : map1.keySet()) {
System.out.println(s+ "======" +map1.get(s));
}
/** 结果
* 张三======3
李四======4
*/
System.out.println( "=====================================" );
//IdentityHashMap中key的内存地址必须完全相同才会覆盖
Map<String,Object> map2 = new IdentityHashMap<>();
map2.put( "张三" , 1 );
map2.put( "张三" , 2 );
map2.put( new String( "张三" ), 3 ); //
map2.put( "李四" , 4 );
for (String s : map2.keySet()) {
System.out.println(s+ "====" +map2.get(s));
}
/**
* 李四====4
张三====2
张三====3
*/
System.out.println( "=====================================" );
Map<Person,Object> map3 = new IdentityHashMap<>();
map3.put( new Person( "张三" , 11 ), 1 );
map3.put( new Person( "张三" , 11 ), 3 );
map3.put( new Person( "李四" , 11 ), 4 );
for (Person s : map3.keySet()) {
System.out.println(s.toString()+ "====" +map3.get(s));
}
/**
* po.Person@165474cf====1
po.Person@3ff2caf4====4
po.Person@2c0cd7d====3
*/
System.out.println( "=====================================" );
Person person = new Person( "张三" , 11 );
Person person2 = new Person( "张三" , 11 );
System.out.println(person.equals(person2));
}
} |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package po;
/** * Created by Administrator on 2015/9/16.
*/
public class Person {
int id;
String name;
int age;
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\ '' +
", age=" + age +
'}' ;
}
@Override
public boolean equals(Object o) {
if ( this == o) return true ;
if (o == null || getClass() != o.getClass()) return false ;
Person person = (Person) o;
if (id != person.id) return false ;
if (age != person.age) return false ;
return !(name != null ? !name.equals(person.name) : person.name != null );
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0 );
result = 31 * result + age;
return result;
}
public Person(String name, int age){
this .name=name;
this .age=age;
}
} |
本文转自Ryan.Miao博客园博客,原文链接:http://www.cnblogs.com/woshimrf/p/4813664.html,如需转载请自行联系原作者