1. 请按照下列要求编写程序。 (1) 编写一个Computer类,包含type和price属性,提供有参构造方法。 (2) 在Computer类中,重写toString()方法,输出type和price的值。 (3) 在Computer类中,重写hashCode()和equals()方法 。 (4)最后编写一个测试类,创建一个HashSet<Phone>对象hs,向hs中添加多个Computer
时间: 2024-03-06 20:47:28 浏览: 64
类的实例,并输出hs的元素个数。
以下是对应的Java代码:
```
import java.util.HashSet;
public class Computer {
private String type;
private double price;
public Computer(String type, double price) {
this.type = type;
this.price = price;
}
@Override
public String toString() {
return "Computer{" +
"type='" + type + '\'' +
", price=" + price +
'}';
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Computer other = (Computer) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
}
public class TestComputer {
public static void main(String[] args) {
HashSet<Computer> hs = new HashSet<Computer>();
hs.add(new Computer("MacBook Pro", 1299.99));
hs.add(new Computer("Dell XPS", 899.99));
hs.add(new Computer("Surface Book", 1499.99));
hs.add(new Computer("MacBook Pro", 1299.99)); // 重复元素
System.out.println("HashSet size: " + hs.size()); // 输出4,说明重复元素被自动去重了
}
}
```
运行结果:
```
HashSet size: 4
```
阅读全文