【发布时间】:2023-03-31 01:35:01
【问题描述】:
我有一个 TreeMap 包含 StockItem 值的映射:
private final Map<StockItem, Integer> list;
我正在使用一种方法来查找此映射中的值,方法是生成一个返回 StockItem 类型的键。
方法如下:
public static StockItem makeKey(String name, double price, int quantityStock){
return new StockItem(name,price,quantityStock);
}
代码运行良好,查找运行良好,我的问题是这到底是怎么可能发生的? makeKey 方法返回一个全新的对象,其中包含可能包含在列表中的完全相同的数据。它是否会经过每次迭代然后调用.equals 来比较每个对象?
这是StockItem 类:
public class StockItem implements Comparable<StockItem> {
private final String name;
private int quantity;
private double price;
private int reserveItems = 0;
public StockItem(String name, double price) {
this.name = name;
this.price = price;
quantity = 0;
}
public StockItem(String name, double price, int quantityStock) {
this.name = name;
this.price = price;
quantity = quantityStock;
}
public void reserveItem(int amountReserved){
this.reserveItems = amountReserved + this.reserveItems;
}
public void unReserveItem(int unreserve){
reserveItems = reserveItems - unreserve;
}
public int getReservedAmount(){
return reserveItems;
}
public String getName() {
return name;
}
public int quantityInStock() {
return quantity;
}
public double getPrice() {
return price;
}
public void adjustStock(int quantity) {
this.quantity = this.quantity + quantity - this.reserveItems;
}
public final void setPrice(double price) {
if (price > 0.0)
this.price = price;
}
public static StockItem MakeKey(String name, double price, int quantityStock){
return new StockItem(name,price,quantityStock);
}
@Override
public int compareTo(StockItem o) {
if (this == o){
return 0;
}
if (o != null){
return this.name.compareTo(o.getName());
}
throw new NullPointerException();
}
public String toString(){
return "Item Name: " + this.name + " Item Price: " + this.price;
}
}
【问题讨论】:
-
请发布 StockItem 代码。
-
@4castle TreeMap
-
@Andreas 好的,所以在 HashMap 中,如果我做了同样的事情,但使用 equals 和 hashcode 也可以吗?
-
@JordanDixon 是的。
标签: java maps equality treemap