Java练习题——集合,(1)编写一个 Student 类,包含 name 和 age 属性,提供有参构造方法。2)在 Student 类中,重写 toString ()方法。

*(1)编写一个 Student 类,包含 name 和 age 属性,提供有参构造方法。
2)在 Student 类中,重写 toString ()方法,输出 age 和 name 的值。
* (3)在 Student 类中,重写 hashCode ()和 equals )方法。 hashCode )的返回值是 name 的哈希值与 age 的和。
* ● equals ()判断对象的 name 和 age 是否相同,相同则返 true ,
* 不同则返回 false 。
(4)编写一个测试类,创建一个 HashSet < Student >对象 hs ,
* 向 hs 中加多个 Student 对象,假设有两个 Student 对象相等。
* 输出 HashSet 集合,观察 Student 对象是否加成功。

代码如下:

package shiyan8;

import java.util.*;
class Student {
    private int age;
    private String name;
    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return age + ":" + name;
    }
    public int hashCode() {
        return name.hashCode() + age;
    }
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!(obj instanceof Student stu))
            return false;
        return this.name.equals(stu.name) && this.age == stu.age;
    }
}

public class Test {
    public static void main(String[] args) {
        HashSet<Student> hs = new HashSet<Student>();
        hs.add(new Student(18, "ZhangSan"));
        hs.add(new Student(20, "lisa"));
        hs.add(new Student(22, "Ikun"));
        System.out.print(hs);
    }
}

运行结果:

  • 18
    点赞
  • 102
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杪商柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值