请按照下列要求编写程序。 I.编写一个Student类,包含name和age属 性,提供有参构造方法。 2在Student类中,重写tosString0方法,输出 age和name的值。 3在Student类中,重写hashCode(和equals) 方法 ahashCode 的返回值是namze的hash值与age 的和。 6equals)判断对象的nameDage是否相同, 相同则返回true不同返回false。 4、最后编写一个测试类,创建一个 Hash.Set Student 对象hs,向hs中添
时间: 2024-03-04 17:49:34 浏览: 24
下面是Python中的实现:
```python
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
def __hash__(self):
return hash(self.name) + self.age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
# 测试代码
s1 = Student("Alice", 18)
s2 = Student("Bob", 20)
s3 = Student("Charlie", 22)
hs = set([s1, s2, s3])
print(hs)
```
解释一下上面的代码:
- Student类有两个属性:name和age,以及一个有参构造方法。
- 重写了__str__方法,用于输出对象的属性。
- 重写了__hash__方法,将name的hash值与age的和作为对象的hash值。
- 重写了__eq__方法,判断两个对象的name和age是否相同。
- 测试代码中,创建了三个Student对象,并将它们添加到一个set中,因为重写了__hash__和__eq__方法,所以set可以正确判断两个对象是否相等。最后输出了这个set,可以看到每个对象只出现了一次,因为它们是相同的。