I have a problem with Hashtable; it contains redundant keys. I have redefined the equal and the hashcode, but the same problem. below is an example of my problem. I'm really need help. Thank you in advance.
public class Payoff {
public ArrayList<Cluster> coalitions = new ArrayList<Cluster>();
@Override
public boolean equals(Object t) {
// Vérification de la référence
if (t==this)
return true;
//Vérification du type du paramètre puis de ses attributs.
if (t instanceof Payoff) {
Payoff tbis = (Payoff)t;
return this.coalitions.equals(tbis.coalitions);
} else
return false;
}
@Override
public int hashCode() {
return this.coalitions.hashCode();
}
}
public class Cluster implements Cloneable {
public ArrayList<Integer> dataArray = new ArrayList<Integer>();
public double[] ch;
public double coalitionPayoff;
public Cluster() {
}
public Cluster(Cluster obj) {
this.ch = obj.ch;
this.dataArray = (ArrayList<Integer>)obj.dataArray.clone();
this.coalitionPayoff = obj.coalitionPayoff;
}
public boolean equals(Object T)
{ // Vérification de la référence
if (T==this)
return true;
//Vérification du type du paramètre puis de ses attributs.
if (T instanceof Cluster)
{
Cluster Tbis = (Cluster) T;
return this.DataArray.equals(Tbis. DataArray) && Arrays.equals(this.Ch,Tbis.Ch)
&& (this.CoalitionPayoff ==Tbis.CoalitionPayoff);
} else
return false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dataArray == null) ? 0 : dataArray.hashCode());
//result = prime * result + (int) (coalitionPayoff ^ (coalitionPayoff >>> 32));
result = prime * result + ((ch == null) ? 0 : ch.hashCode());
return result;
}
public Cluster clone() {
return new Cluster ();
}
}
public static void main(String[] args) throws Exception {
Hashtable<Payoff,Double> HashTab = new Hashtable<Payoff,Double>();
Payoff Pay1 = new Payoff();
Cluster Cluster1 = new Cluster();
Cluster1.DataArray.addAll(java.util.Arrays.asList(1,2,3));
double[] ary = {1.5};
Cluster1.Ch= ary;
Pay1.Coalitions.add(Cluster1);
Cluster1 = new Cluster();
Cluster1.DataArray.addAll(java.util.Arrays.asList(4,5));
double[] ary2 = {4.5};
Cluster1.Ch= ary2;
Pay1.Coalitions.add(Cluster1);
HashTab.put(Pay1, 0.5);
Payoff Pay2 = new Payoff();
Cluster Cluster2 = new Cluster();
Cluster2.DataArray.addAll(java.util.Arrays.asList(1,2,3));
double[] ary3 = {1.5}; Cluster2.Ch= ary3;
Pay2.Coalitions.add(Cluster2);
Cluster2 = new Cluster();
Cluster2.DataArray.addAll(java.util.Arrays.asList(4,5));
double[] ary4 = {4.5};
Cluster2.Ch= ary4;
Pay2.Coalitions.add(Cluster2);
if(!HashTab.containsKey(Pay2)){
HashTab.put(Pay2, 0.5);
}
System.out.println(HashTab.size());
}