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

本文介绍了一个Java程序示例,定义了Student类并重写了toString(), equals() 和 hashCode() 方法。通过HashSet验证对象唯一性,并展示了如何使用迭代器遍历集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

1 编写一个Student类,包含nameage属性,提供有参构造方法。

2 Student类中,重写toString()方法,输出agename的值。

3 Student类中,重写hashCode()equals()方法

  1. hashCode()的返回值是namehash值与age的和。
  2. equals()判断对象的nameage是否相同,相同则返回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);
        }

    }
}

,观察是否添加成功。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值