码迷,mamicode.com
首页 > 其他好文 > 详细

集合:Hashset的唯一性

时间:2018-08-02 20:44:00      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:name   成员方法   super   创建   als   list   string   equals   唯一性   

第一部分:

//创建学生类
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student(){
super();
}

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 boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;

Student student = (Student) o;

if (getAge() != student.getAge()) return false;
return getName() != null ? getName().equals(student.getName()) : student.getName() == null;

}

@Override
public int hashCode() {
int result = getName() != null ? getName().hashCode() : 0;
result = 31 * result + getAge();
return result;
}

@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}

第二部分:
public class Set {
public static void main(String[] args){
//创建集合对象
HashSet<Student> list = new HashSet<>();
//创建学生对象
Student s1 = new Student("苏有朋",38);
Student s2 = new Student("林志颖",40);
Student s3 = new Student("蔡依林",35);
Student s4 = new Student("林志颖",40);
Student s5 = new Student("苏有朋",38);
Student s6 = new Student("张无忌",28);
Student s7 = new Student("周芷若",18);
//添加到集合
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
//遍历新的集合
for (Student x:list){
System.out.println(x.getName()+"----"+x.getAge());
}
}
}

集合:Hashset的唯一性

标签:name   成员方法   super   创建   als   list   string   equals   唯一性   

原文地址:https://www.cnblogs.com/WTBK/p/9409256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!