目錄
1、Set接口的一個實現類,它不保證Set的迭代順序,特別是它不保證該順序恆久不變。
2、唯一性:底層依賴於hashCode()和equals()方法。
一、 Set<object>接口
1、Set接口特點:無序的,唯一的
- 存儲順序和取出順序不一致,有自己的存儲順序
- 不可重複
- List接口:有序的,可重複
程序代碼:
package hashset.cn;
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new HashSet<String>();
set.add("hello");
set.add("world");
set.add("java");
set.add("hello");
set.add("world");
set.add("java");
for(String s: set) {
System.out.println(s);
}
}
}
輸出結果:
二、HashSet<object>類
1、Set接口的一個實現類,它不保證Set的迭代順序,特別是它不保證該順序恆久不變。
2、唯一性:底層依賴於hashCode()和equals()方法。
程序代碼:
package hashset.cn;
import java.util.HashSet;
public class HashSetOnlyDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Student> hs = new HashSet<Student>();
Student stu1 = new Student("彰顯",22);
Student stu2 = new Student("魔女",23);
Student stu3 = new Student("繡逗",19);
Student stu4 = new Student("彰顯",22);
Student stu5 = new Student("張翰",22);
Student stu6 = new Student("張哈",22);
hs.add(stu1);
hs.add(stu2);
hs.add(stu3);
hs.add(stu4);
hs.add(stu5);
hs.add(stu6);
for(Student s: hs) {
System.out.println(s.getName()+":"+s.getAge());
}
}
}
輸出結果:
程序結果中有重複的元素,並沒有保證唯一性,這是因爲Student類中沒有重寫hashCode()和equals()方法,上面Set中第一個程序用的是String類,String重寫了hashCode()和equals()方法,所以保證了唯一性。hashCode()如果沒有重寫,則該類的兩個對象無論如何都不會相等
程序代碼:
package hashset.cn;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
this.name = name;
this.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;
}
@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;
Student other = (Student) 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;
}
}
輸出結果:
關於hashCode()和equals():
hashCode()方法的作用是獲取哈希碼(散列碼)
兩者的規定:
- 如果兩對象相等,則hashCode()一定相等。
- 兩對象相等,則調用equals()都返回true。
- 兩對象有相同的hashCode值,他們也不一定相等(物理內存上不同,邏輯值上相同,雜湊算法中容易出現碰撞)。
- equals()被覆蓋,則hashCode()也必須被覆蓋。
- hashCode()的默認行爲是對堆上的對象產生獨特值,hashCode()如果沒有重寫,則該類的兩個對象無論如何都不會相等(即便是指向相同的數據)