标签:存在 .com system span 变化 shc ati int return
public class TestSet {
@Test
public void TestHashSet() {
Set set1 = new HashSet();
set1.add(null);// 可以存null
set1.add(1);
set1.add(2);
set1.add(new String("A"));
set1.add(new String("A"));// 不可重复性(依赖于 equals()和 hashCode()方法)
set1.add("B");
System.out.println(set1);// [null, 1, A, 2, B]
Set set2 = new HashSet();
set2.add(2);
set2.add(null);
set2.add("B");
set2.add(1);
set2.add("A");
System.out.println(set2);// [null, 1, A, 2, B],无序性
}
}
public class TestSet2 {
public static void main() {
Set set = new HashSet();
set.add(new Person1("aa"));
set.add(new Person1("aa"));
set.add(new Person2("aa"));
set.add(new Person2("aa"));// Person2 没有重写 hashCode()方法,此时调用的是 Object类定义的hashCode()方法,算出哈希值不一样,所以可以存储
System.out.println(set);// [Person2 [name=aa], Person2 [name=aa],Person1 [name=aa]]
}
}
class Person1 {
private String name;
@Override
public String toString() {
return "Person1 [name=" + name + "]";
}
public Person1(String name) {
super();
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person1 other = (Person1) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
class Person2 {
private String name;
public Person2(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Person2 [name=" + name + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person2 other = (Person2) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
标签:存在 .com system span 变化 shc ati int return
原文地址:http://www.cnblogs.com/chendifan/p/6535666.html