Java - TreeSet accepting duplicates

190
May 03, 2018, at 06:03 AM

I'm having some problems with TreeSet: why does this one accept duplicates? I thought TreeSets detected them through the Comparator, and automatically remove them. Please help me, I'm kind of new to both Java and StackOverflow.

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class SortedSongs
{   
    private Set songs;
    public SortedSongs()
    {
         Comparator<Song> comp = (Song c1, Song c2)-> c1.toString().compareTo(c2.toString());
         songs = new TreeSet<>(comp);
    }
}

edit: this is how I implemented hashCode and equals:

@Override
public int hashCode()
{
    return Objects.hash(name, author);
}
@Override
public boolean equals(Object o)
{
    return o == null ? false : o.getClass() != getClass() ? false
        : o.hashCode() == hashCode();
}

is it wrong?

Answer 1

TreeSet is implemented with a balanced binary tree in Java (actually RedBlack tree) . So it does not use the equals method. It uses the Comparator.

Now the problem about your implementation is about your comparator. Your comparator is based on the toString method. By default java returns the name of the object's class plus its hash code. So by default the output of toString will be the same for two objects if and only if they are pointing to the same memory reference. You need to make sure that you have override the toString method in your class as you comparator is based on that.

To resolve the issue, you need to define a comparator that reflect the comparison logic of your program.

Rent Charter Buses Company
READ ALSO
How do I stop JEditorPane from auto-indenting subsequent text?

How do I stop JEditorPane from auto-indenting subsequent text?

My program loads an RTF file and displays it in a JEditorPane with the following code:

164
Camel - Designing scalable dynamic dataflow

Camel - Designing scalable dynamic dataflow

Use case: I receive a message from a source endpointDepending on the type of message, it gets handled by completely different business logic (e

179
Java app in docker: Failed to get driver instance for postgres

Java app in docker: Failed to get driver instance for postgres

I created a java web appWhen I run java -jar xxx

266
Nested hash map with hash map

Nested hash map with hash map

i want to create a hashmap that return this output:

211