HastSet无序即放入其中的对象不一定按放入顺序输出;不能去重复对象即如果放入集合中的对象没有重写hashcode和equal,是不能去除重复值的,也就是说内容相同的对象能够同时存在;TreeSet有序,放入其中的对象按顺序排列;能够去掉重复值,即内容相同的对象不能同时存在。
误区提示:以下代码1不可被重复加入,此时1会自动装箱成Integer类型,内部已实现hashcode和equals
HashSet set = new HashSet();
set.add(1);
set.add(1);
重写hashcode和equal
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
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;
User other = (User) obj;
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;
}
类全代码
class User implements Comparable<User> {
private String name;
private int age;
@Override
public int compareTo(User user) {
// TODO Auto-generated method stub
// >0 =0 <0
int result = this.age - user.age;
// name即this.name
if (name == null || user.name == null) {
throw new RuntimeException("name is null");
} else {
result = this.name.compareTo(user.name);
}
return result;
}
// 只要两个对象的name 和age 是相同的hashcode值就是相同的.
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
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;
User other = (User) obj;
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 User(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
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;
}
}
HashSet,TreeSet测试代码
public class List {
public static void main(String[] args) {
User user1 = new User("a", 51);
User user2 = new User("b", 51);
User user3 = new User("c", 51);
System.out.println(user1.hashCode());
User user4 = new User("d",51);
User user5 = new User("d",51);
// TreeSet set = new TreeSet();
HashSet set = new HashSet();
set.add(user1);
set.add(user2);
set.add(user3);
set.add(user4);
set.add(user5);
// set.toArray().length;
System.out.println(set);
// String mString = null;
// System.out.println(mString);
// ArrayList mArrayList=new ArrayList<>();
// mArrayList.add("a");
// mArrayList.add("b");
// mArrayList.add("c");
// mArrayList.add("d");
// mArrayList.add("e");
// System.out.println(mArrayList);
// mArrayList.add(2,"z");
// System.out.println(mArrayList);
}
}