0

嘿大家。我是 Java 新手,我有这样的 2D LinkedList:

LinkedList<LinkedList<String>> albums = new LinkedList<LinkedList<String>>();

其中充满了如下数据:

if (!artist.isEmpty() && !name.isEmpty()) {
    albums.add(new LinkedList<String>());
    albums.getLast().add(artist.toString());
    albums.getLast().add(name.toString());
}

但我想确保我的列表没有重复的专辑。如何检查我的专辑列表是否已经包含相同的艺术家姓名

4

2 回答 2

2

是的,评论者是对的。Album使用artistandname字段创建一个类并在它们上实现equals()(and hashCode())。然后您可以使用它contains()来查找重复项。或者甚至考虑使用 a Set(但前提是在您的类上确实定义了哈希码,因为集合由哈希支持)。

于 2009-12-11T23:54:29.597 回答
2

我的建议是创建一个名为 Album 的新类,它看起来像这样:

public class Album
{
    private String name;
    private String artist;

    public Album(String name, String artist)
    {
        this.name = name;
        this.artist = artist;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getArtist()
    {
        return artist;
    }

    public void setArtist(String artist)
    {
        this.artist = artist;
    }

    public boolean equals(Object o)
    {
        if (o instanceof Album)
        {
            Album that = (Album)o;
            return album.equals(that.album) && artist.equals(that.artist);
        }
        else
        {
            return false;
        }
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((album == null) ? 0 : album.hashCode());
        result = prime * result + ((artist == null) ? 0 : artist.hashCode());
        return result;
    }
}

Then you should be able to use contains() to check whether or not the album already exists in the linked list.

于 2009-12-11T23:56:06.657 回答