-1

我有一个名为 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);



    }


}
4

1 回答 1

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]
于 2013-07-29T21:01:20.497 回答