总之,你应该重写Object
类的equals
方法。
由于没有在栅极是否被保存为一个数组没有信息,一个List
/Set
(Collection
)或者作为不同的class
共一个目的,提供了所有三种解决方案。
@Override
public boolean equals(Object other) {
if(other == null)
return false; // Nothing is equal to null, other than null (in which case
// this method would not be callable)
if(this == other)
return true; // They are already the same reference
if(!(other instanceof Airport))
return false; // An Airport can not be considered equal to a non-Airport object
Airport port = (Airport) other; // This cast is now safe, as other must
// be of type Airport
// Until next END, this can be removed if airportCode can never be null
if(airportCode == null) {
if(port.airportCode != null)
return false; // "Mine is null, theirs is not."
}
// END
if(!port.airportCode.equals(airportCode))
return false; // "Their code is different from our."
// IF gates is an array, note that this distorts any ordering that is non-comformant
// with the natural order imposed by the compareTo-method
Object[] otherGates = port.gates;
Arrays.sort(gates); // Sort our gates
Arrays.sort(otherGates); // Sort their gates
return Arrays.equals(gates, otherGates); // This may need overwriting the equals
// method of the gates, if it isn't a String
// IF gates is a collection, again, may distort orderings
List<?> otherGates = port.gates; // Replace the ? with the type
Comparator<?> c = null; // Again, replace the ?. Assign an implementation of Comparator
// if ? does not implement Comparable on its own
gates.sort(c); // Sort our gates
otherGates.sort(c); // Sort their gates
return gates.equals(otherGates); // This may need overwriting the equals
// method of the gates, if it isn't a String
// Now at last, if the gates are an object all of their own
Gates otherGates = port.gates;
return gates.equals(otherGates); // Needs an overwriting of equals in class Gates
}
请注意,这可以做得更加简洁,但它显示的方式更容易理解,并且由于给出的信息不完整。
到目前为止你已经尝试过。这是你的功课吗?抱歉。 –
首先尝试自己编码,然后再问问题 – Jonas
是的,就像我没有尝试过。这正是我所尝试过的完全错误的。也不,不是功课。只是一个实验室来帮助我理解。 – johnrh