2D LinkedList.contains() in Java
-
19-09-2019 - |
Question
Hey, everyone. I'm new to Java and I have 2D LinkedList like this:
LinkedList<LinkedList<String>> albums = new LinkedList<LinkedList<String>>();
Which is filled with data like so:
if (!artist.isEmpty() && !name.isEmpty()) { albums.add(new LinkedList<String>()); albums.getLast().add(artist.toString()); albums.getLast().add(name.toString()); }
But I want to make sure my list has no duplicate albums. How to check whenever my albums list already contains same pair of artist and name?
Solution
My suggestion would be to create a new class, called Album that looks something like this:
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.
OTHER TIPS
Yes, commenter is right. Create a class Album
with artist
and name
fields and implement equals()
(and hashCode()
) on them. And then you can use contains()
to find the duplicate. Or even consider using a Set
(but only if hash code is really defined on your class, since a set is backed by a hash).