如何解决问题:不能取消引用int [英] How to solve the problem: int cannot be dereferenced
问题描述
在这里,我有一些值,其中两个是整数,并且由于它们未被引用,因此无法在它们上调用方法.我该如何解决?
Here I have some value which two of them are integer and I can't call a method on them since they are not reference. How can I solve this?
String srcAddr, dstAddr, protocol;
int srcPort, dstPort;
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dstAddr == null) ? 0 : dstAddr.hashCode());
result = prime * result + ((dstPort == null) ? 0 : dstPort.hashCode());
result = prime * result + ((srcAddr == null) ? 0 : srcAddr.hashCode());
result = prime * result + ((srcPort == null) ? 0 : srcPort.hashCode());
return result;
}
此外,我也有一个相等的方法,下面显示了一部分错误,该错误与上面的相同,我无法将int与null进行比较.
Also, I have an equal method too, a part of it with the error is shown below ,which the same as above I can not compare int with a null.
@Override
public boolean equals(Object obj) {
if (srcPort == null) {
if (other.srcPort != null)
return false;
} else if (!srcPort.equals(other.srcPort))
return false;
if (srcPort == null) {
if (other.srcPort != null)
return false;
} else if (!srcPort.equals(other.srcPort))
return false;
}
如何解决此错误?
推荐答案
对于 hashcode
方法,您可以直接保留整数.整数是它们自己的hascodes.对于 equals
方法,只需使用 =
进行比较即可.因此代码变为:
For the hashcode
method, you can just leave the ints as they are. Ints are their own hascodes. For the equals
method, just compare them using =
. So the code becomes:
public class Connection {
String srcAddr, dstAddr, protocol; int srcPort, dstPort;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dstAddr == null) ? 0 : dstAddr.hashCode());
result = prime * result + dstPort;
result = prime * result
+ ((protocol == null) ? 0 : protocol.hashCode());
result = prime * result + ((srcAddr == null) ? 0 : srcAddr.hashCode());
result = prime * result + srcPort;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Connection other = (Connection) obj;
if (dstAddr == null) {
if (other.dstAddr != null)
return false;
} else if (!dstAddr.equals(other.dstAddr))
return false;
if (dstPort != other.dstPort)
return false;
if (protocol == null) {
if (other.protocol != null)
return false;
} else if (!protocol.equals(other.protocol))
return false;
if (srcAddr == null) {
if (other.srcAddr != null)
return false;
} else if (!srcAddr.equals(other.srcAddr))
return false;
if (srcPort != other.srcPort)
return false;
return true;
}
}
编写 hashCode
和 equals
的正确实现非常棘手.更好地使用您的IDE生成它们.这也是我在这里所做的.
Writing correct implementations of hashCode
and equals
is tricky. Better use your IDE to generate them. That's what I did here too.
这篇关于如何解决问题:不能取消引用int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!