编写一个Student类,包含name和age属性,提供有参构造方法

  • Post author:
  • Post category:其他



2.


请按照下列要求编写程序。





1





编写一个


Student


类,包含


name





age


属性,提供有参构造方法。





2








Student


类中,重写


toString()


方法,输出


age





name


的值。





3








Student


类中,重写


hashCode()





equals()


方法


  1. hashCode()


    的返回值是


    name





    hash


    值与


    age


    的和。

  2. equals()


    判断对象的


    name





    age


    是否相同,相同则返回


    true


    不同返回


    false







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);
        }

    }
}


,观察是否添加成功。



版权声明:本文为m0_60696519原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。