我有一个名为 Mountain 的类,我在其中重写 hashCode() 和 equals() 方法,以便在 HashSet 中使用,这样我就不会得到重复项。但无论如何,我还是重复了 Mountains。我无法理解我在搞砸什么。代码实现:
package Unidad16;
public class Mountain{
String Name;
int Heigh;
Mountain(String n,int h){
this.Name=n;
this.Heigh = h;
}
public void setName(String name){
this.Name=name;
}
public String getName(){
return this.Name;
}
public void setHeigh(int Heigh){
this.Heigh=Heigh;
}
public int getHeigh(){
return this.Heigh;
}
public String toString(){
return this.Name;
}
@Override
public boolean equals(Object aMountain){
if(!(aMountain instanceof Mountain)){
return false;
}
Mountain m = (Mountain) aMountain;
return this.Name.equals(m.getName());
}
@Override
public int hashCode(){
return this.Name.hashCode();
}
}
package Unidad16;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
public class MainCompara {
public static void main(String args[]){
List<Mountain> listaMontanas = new ArrayList<Mountain>();
listaMontanas.add(new Mountain("Loma Cabrera", 2000));
listaMontanas.add(new Mountain("Loma Cabrera", 2000));
listaMontanas.add(new Mountain("Pico Duarte", 2000));
listaMontanas.add(new Mountain("Pico Duarte", 2000));
listaMontanas.add(new Mountain("Pico Duarte", 2000));
listaMontanas.add(new Mountain("Pico Duarte", 2000));
listaMontanas.add(new Mountain("Montaña X", 3000));
listaMontanas.add(new Mountain("Montaña X", 3000));
//Collections.sort(listaMontanas);
System.out.println(listaMontanas);
System.out.println("**************************************************");
HashSet<Mountain> miSet = new HashSet<Mountain>();
miSet.addAll(listaMontanas);
System.out.println(listaMontanas);
}
}