Edge のセットを保存したい:
class Edge {
int u;
int v;
char symbol;
}
問題は、2 つのEdgeオブジェクトが同じu,vとを持つ可能性symbolがあることですが、同じオブジェクトと見なしたい場合でも、同じオブジェクトではないため、両方を HashSet に格納できます。u一意の ( 、v、symbol)を持つオブジェクトを 1 つだけ格納するにはどうすればよいSetですか?
Edge のセットを保存したい:
class Edge {
int u;
int v;
char symbol;
}
問題は、2 つのEdgeオブジェクトが同じu,vとを持つ可能性symbolがあることですが、同じオブジェクトと見なしたい場合でも、同じオブジェクトではないため、両方を HashSet に格納できます。u一意の ( 、v、symbol)を持つオブジェクトを 1 つだけ格納するにはどうすればよいSetですか?
You need to override the following two methods equals and hashcode.
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Edge)) return false;
// return true if they are the same, otherwise false
}
public int hashCode() {
// return an int that represents similarity
// Example: name.hashCode(), if they are the same with the same name
}
使用するセットの種類によって異なります。以下は、たとえば HashSet に適用されますが、SortedSet のサブクラスには適用されません
equals()とhashCode( ) をオーバーライドすることにより:
class Edge {
int u;
int v;
char symbol;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + symbol;
result = prime * result + u;
result = prime * result + v;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Edge other = (Edge) obj;
return symbol == other.symbol && u == other.u && v == other.v;
}
}
オーバーライドする必要がありますequals()。このような:
public boolean equals(Object obj) {
//do the comparison here; remember to cast obj to Edge
}