Issue
I wrote a generic class to rapresent an Object that has two generic types, like this:
public class Arco<N extends Comparable<N>,L extends Comparable<L>> implements Comparable<Arco<N, L>> {
private N node1, node2; //start and end node
private L label; //node label
//Arch constructors
public Arco() {
node1 = node2 = null;
label = null;
}
public Arco(N x1, N y1, L l) {
node1 = x1;
node2 = y1;
label = l;
}
in this class I have overrided the methods equals, compareTo and hashcode like this:
//override methods to compare Archs
public boolean equals(Arco<N, L> a) {
if (a instanceof Arco) {
Arco<N, L> arc = a;
return (node1.equals(arc.node1) && node2.equals(arc.node2) && label.equals(arc.label));
}
return false;
}
@Override
public int hashCode() {
int result = label != null ? label.hashCode() : 0;
result = 31 * result + (node1 != null ? node1.hashCode() : 0);
result = 31 * result + (node2 != null ? node2.hashCode() : 0);
return result;
}
@Override
public int compareTo(Arco<N, L> a) {
int i = this.label.compareTo(a.label);
if (i == 0) {
int j = this.node1.compareTo(a.node1);
if (j == 0)
return this.node2.compareTo(a.node2);
else
return j;
} else {
return i;
}
}
now in another class I have an Hashmap like this that contains a Set of Arco objects:
public class Grafo <N extends Comparable<N>,L extends Comparable<L>> {
HashMap<N, Set<Arco<N, L>>> nodi; //lista dei nodi
int nArchi; //numero Archi
boolean diretto; //informazione sul tipo di grafo diretto= true non diretto =false
//Costructor
public Grafo(boolean diretto) {
nodi = new HashMap<N, Set<Arco<N,L>>>();
nArchi = 0;
this.diretto = diretto;
}
in this last class i wrote a method:
public boolean containsArch(N x, N y, L label){
Arco<N,L> a = new Arco<N,L>(x,y,label);
if (nodi.containsKey(x)&&nodi.containsKey(y)){
return nodi.get(x).contains(a);
}
return false;
}
my problem now is that sems that .contains(a)
does not work , I supposed is because of the comparison wrong from the Arco object but I don't know how to do it in a better way.
I noticed that also .remove(Arco)
doesn't work
I hope you can help me. thank you!
Solution
Unfortunately, you didn't override equals
. Instead of
public boolean equals(Arco<N,L> a) {
you must write
public boolean equals(Object a) {
and use instanceof
and cast appropriately.
Answered By - Louis Wasserman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.