終極HashSet HashMap TreeSet TreeMap深入分析上
首先講解HashSet
Set<String> set = new HashSet<>();
set.add("e");
set.add("a");
set.add("b");
System.out.println(set); //如果穿的是int String 就會自增
Set<User> set1 = new HashSet<>();
set1.add(new User(21,"張三"));
set1.add(new User(22,"里斯"));
set1.add(new User(23,"zhangsan")); //
set1.add(new User(23,"zhangsan")); //不想存入相同 重寫equals hashcode
下面附上重寫的程式碼
User類
class User{
private int age;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [age=" + age + ", name=" + name + "]";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User( int age,String name) {
super();
this.name = name;
this.age = age;
}
}
@Override
public int hashCode() {
System.out.println("我是hashcode");
return this.name.hashCode();
}
@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;
}
下面介紹TreeSet
Set<String> set = new TreeSet<>();
set.add("a");
set.add("c");
set.add("e");
set.add("d");
System.out.println(set);///如果穿的是基本型別(int,string) 自增
Set<User2> set2 = new TreeSet<>(new myCom2()); //此時User2跟User1一樣 只不過不是公共類一個包中只能有一個
set2.add(new User2(21,"張三"));
set2.add(new User2(22,"張三2"));
set2.add(new User2(23,"張三3")); //TreeSet不想存放物件2種方式 1、實現comparable介面2、編寫一個類繼承comparator
set2.add(new User2(23,"張三3")); //TreeSet不想存放物件2種方式
System.out.println(set2);
第二種:
class myCom2 implements Comparator<User2>{
@Override
public int compare(User2 o1, User2 o2) {
// TODO Auto-generated method stub
return o1.getAge() - o2.getAge();
}
}
第一種: implements Comparable<User2>
@Override
public int compareTo(User2 o) {
// TODO Auto-generated method stub
if(this.age > o.age) {
return 1;
}else if(this.age < o.age) {
return -1;
}
return 0;
}
下篇介紹map中的方法