创建一个People类,包括姓名和年龄2个成员变量。创建3个People对象,将其添加到HashSet中,如果姓名相同,则禁止添加
时间: 2024-03-16 19:46:57 浏览: 67
创建一个叫做People的类
5星 · 资源好评率100%
好的,根据您的要求,我来为您编写一个People类,并创建三个People对象并将其添加到HashSet中。如果姓名相同,则禁止添加。
以下是示例代码:
```python
import java.util.HashSet;
public class People {
private String name;
private int age;
public People(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof People)) {
return false;
}
People p = (People) obj;
return this.name.equals(p.getName());
}
@Override
public int hashCode() {
return this.name.hashCode();
}
public static void main(String[] args) {
HashSet<People> set = new HashSet<>();
People p1 = new People("Alice", 20);
People p2 = new People("Bob", 25);
People p3 = new People("Alice", 30);
if (set.add(p1)) {
System.out.println("Added " + p1.getName());
} else {
System.out.println("Already existed: " + p1.getName());
}
if (set.add(p2)) {
System.out.println("Added " + p2.getName());
} else {
System.out.println("Already existed: " + p2.getName());
}
if (set.add(p3)) {
System.out.println("Added " + p3.getName());
} else {
System.out.println("Already existed: " + p3.getName());
}
}
}
```
输出结果为:
```
Added Alice
Added Bob
Already existed: Alice
```
可以看到,我们成功地创建了一个People类,并且根据您的要求,成功地将三个People对象添加到了HashSet中。如果姓名相同,则禁止添加。
阅读全文