publicclassGenericSet{publicstaticvoidmain(String[]args){Setset=newHashSet();set.add("aa");set.add("bb");set.add("cc");set.add("dd");for(Iteratori...
public class GenericSet {
public static void main(String[] args) {
Set set = new HashSet();
set.add("aa");
set.add("bb");
set.add("cc");
set.add("dd");
for(Iterator iter = set.iterator(); iter.hasNext();){
String value = iter.next();
System.out.println(value);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
Set set2 = new HashSet();
set2.add(new People("zhangsan",18,"luoyang"));
set2.add(new People("lisi",18,"zhengzhou"));
set2.add(new People("wangwu",18,"beijing"));
for(Iterator iter = set2.iterator();iter.hasNext();){
People people = iter.next();
String name = people.getName();
int age = people.getAge();
String Address = people.getAddress();
System.out.println(name+","+age+","+Address);
}
}
}
class People{
private String name;
private int age;
private String Address;
public People(String name, int age, String Address){
this.name = name;
this.age = age;
this.Address = Address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((Address == null) ? 0 : Address.hashCode());
result = prime * result + age;
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;
People other = (People) obj;
if (Address == null) {
if (other.Address != null)
return false;
} else if (!Address.equals(other.Address))
return false;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
这个里面people类里面 为什么要生成hashcode和equals这两个方法? 不生成这两个方法这个程序照样可以运行,没有受影响啊? hashcode和equals这两个方法何时需要被重写啊?
展开