gpt4 book ai didi

java - 在列表中包含和删除实例用户定义类的方法?

转载 作者:行者123 更新时间:2023-12-04 04:51:35 24 4
gpt4 key购买 nike

所以我有这个代码:

List<MyDataType> test = map.get(id)
MyDataType test1 = new MyDataType("XXX", 1);
System.out.println(test.contains(test1)); // returns false
System.out.println(test.get(0).equals(test1)); // returns true
System.out.println(test.remove(test1)); // returns false
System.out.println(test); // still the original list

我已经覆盖了 .equals.hashCode() MyDataType 中的方法,并且是一致的。此外, map类型为 ListMultimap<Long, DestQuanTuple> (忘了在我的 OP 中提到这一点。)但是,电话: map.remove(sourceContainerId, test1)不修改 test要么。
MyDataType类(class):
public class MyDataType implements Comparable<MyDataType> {
private String destination;
private int quantity;

// Constructor initializes destination and quantity

// Getters exist to get destination and quantity

public boolean equals (MyDataType other) {
boolean destinationSame = false, quantitySame = false;
destinationsame = this.getDestination().equals(other.getDestination());
Integer thisQuantity = (Integer) this.getQuantity();
Integer otherQuantity = (Integer) other.getQuantity();
quantitySame = thisQuantity.equals(otherQuantity);
return destinationSame && quantitySame;
}

public int hashCode() {
return destination.hashCode() + quantity;
}

public int compareTo(MyDataType other) {
Integer myQuantity = this.getQuantity();
if (myQuantity.compareTo(other.getQuantity()) != 0) {
return myQuantity.compareTo(otherTuple.getQuantity());
}
else {
return this.getDestination().compareTo(otherTuple.getDestination());
}
}
}

知道为什么我没有得到我想要的功能吗?

最佳答案

您遇到的问题是您必须定义 equalshashCode一致

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null :
o.equals(e))
.



契约(Contract)是 a.equals(b), then a.hashCode() must be same as b.hashCode().
结论,你必须覆盖 equalshashCode
更新
 public boolean equals (MyDataType other) {

}

必须是,
 @Override
public boolean equals (Object other) {

}

请注意,如果您使用覆盖注释,那么如果出现错误将无法编译,因此请使用注释!

您正在重载等于这通常不是必需的,因为它很难维护,在您的情况下,意外行为成为导致集合使用默认值 equals(Object o)这就是为什么你有那个。

关于java - 在列表中包含和删除实例用户定义类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com