Java HashSet仍然允许重复

时间:2013-07-29 20:58:19

标签: java collections hashset

我有一个名为Mountain的类,我在其中覆盖hashCode()和equals()方法以便在HashSet中使用,这样我就不会重复了。但无论如何,我正在重复山脉。我无法得到我搞砸的东西。代码实现:

  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);



    }


}

1 个答案:

答案 0 :(得分:4)

这是问题(最后一行):

System.out.println(listaMontanas);

你的意思是:

System.out.println(miSet);

目前你只是打印出两次列表,而不是第二次打印出来。

通过该更改,输出为:

[Loma Cabrera, Loma Cabrera, Pico Duarte, Pico Duarte, Pico Duarte, Pico Duarte,
 Montaña X, Montaña X]
**************************************************
[Loma Cabrera, Montaña X, Pico Duarte]