赞
踩
2. 请按照下列要求编写程序。
(1) 编写一个Student类,包含name和age属性,提供有参构造方法。
(2) 在Student类中,重写toString()方法,输出age和name的值。
(3) 在Student类中,重写hashCode()和equals()方法
(4)最后编写一个测试类,创建一个HashSet<Student>对象hs,向hs中添加多个Student对象,假设有两个Student对象相等,输出HashSet
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Objects;
-
- public class Student {
- public String name;
- public int age;
-
- public Student(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Student student = (Student) o;
- return age == student.age &&
- Objects.equals(name, student.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name)+age;
- }
- }
-
- class TestStudent{
- public static void main(String[] args) {
- Student stu=new Student("曹操",12);
- Student stu1=new Student("刘备",19);
- Student stu2=new Student("孙策",17);
- Student stu3=new Student("孙斌",18);
- Student stu4=new Student("孙斌",18);
-
- HashSet<Student> hs=new HashSet<>();
- hs.add(stu1);
- hs.add(stu2);
- hs.add(stu3);
- hs.add(stu4);
- hs.add(stu);
- System.out.println(hs);
- Iterator it=hs.iterator();
- while (it.hasNext()){
-
- System.out.println(it.next());
- }
-
- for (Object i:hs
- ) {
- System.out.println(i);
- }
-
- }
- }
,观察是否添加成功。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。