總之,你應該重寫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