Set集合及理解1
Set集合
按照无序且不允许重复的方式来存放对象。其无序体现在没有下标上,因此,其没有get()方法。
特点:
无序存储,不能存储相同元素,也不能通过下标访问。
HashSet
HashSet是Set接口的具体实现,HashSet的底层结构基于一个可以快速查找的散列表(Hash table)结构,其也称为哈希表,采用了按照对象的取值计算对象存储地址的策略,实现了“定位存放”,同时也提高了查找效率。哈希表是一种元素为链表的数组,具有二者的优点。
具体实现
- 代码1
public class Student {
private String name;//定义名字
private int 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;
}
public Student(){}
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return "Student是"+"name:"+name+"age:"+age;
}
}
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String []args){
Set set = new HashSet();
set.add(new Student("xiaoming",11));
set.add(new Student("xiaowang",13));
set.add(new Student("xiaolan",12));
set.add(new Student("xiaoming",11));
for(Object student:set){
System.out.println(student);
}
}
}
在上述代码中,输出只会原原本本地输出,而不会起到去除重复的效果,因此达不到理想的结果,为了得到期望的效果,需要在代码上进行对hashCode()和equals()方法的重写.
- 代码2
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String []args){
Set set = new HashSet();
set.add(new Student("xiaoming",11));
set.add(new Student("xiaowang",13));
set.add(new Student("xiaolan",12));
set.add(new Student("xiaoming",11));
for(Object student:set){
System.out.println(student);
}
}
}
public class Student {
@Override
public int hashCode(){
final int prime = 3;
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;
Student other = (Student)obj;
if(name == null){
if(other.name != null){
return false;
}
}else if(!name.equals(other.name))
return false;
return true;
}
private String name;
private int 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;
}
public Student(){}
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return "Student是"+"name:"+name+"age:"+age;
}
}
代码1效果图:
代码2效果图: