往HashSet集合中添加3个电脑对象,要求品牌、价格、颜色相同,就认为是同一个对象,同一个对象只允许存在一个。
时间: 2023-05-19 10:05:43 浏览: 59
可以使用以下代码实现:
```
HashSet<Computer> set = new HashSet<>();
Computer computer1 = new Computer("Dell", 5000, "black");
Computer computer2 = new Computer("Dell", 5000, "black");
Computer computer3 = new Computer("Dell", 5000, "black");
set.add(computer1);
set.add(computer2);
set.add(computer3);
class Computer {
private String brand;
private int price;
private String color;
public Computer(String brand, int price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
@Override
public int hashCode() {
return Objects.hash(brand, price, color);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Computer computer = (Computer) obj;
return price == computer.price &&
Objects.equals(brand, computer.brand) &&
Objects.equals(color, computer.color);
}
}
```
这里定义了一个Computer类,重写了hashCode()和equals()方法,保证同一个品牌、价格、颜色的电脑对象被认为是同一个对象。然后创建了三个电脑对象,添加到HashSet集合中。