Yass
Yass

Reputation: 25

Putting element into TreeMap Java

I'm trying to use a TreeMap to store my data, but i have a problem to add new element into it.

public class Graph {

private TreeMap<Vertex, ArrayList<Vertex>> tree;

public Graph() {
    this.tree = new TreeMap<>();
}

public void addVertex(int label) {
    this.tree.put(new Vertex(label), new ArrayList<Vertex>());
}

When I use my addVertex method, I don't have error but when I display my map, I only have 1 element into my treemap : {1=[]}

public class Main {

public static void main(String[] args) {
  Graph g = new Graph();


  g.addVertex(1);
  g.addVertex(2);
  g.addVertex(3);
  g.addVertex(4);

I tryed to create a basic map like that :

TreeMap<Integer, String> map = new TreeMap<Integer, String>();
  map.put(1, "dog");
  map.put(2, "cat");

  System.out.println(map);

And it works, so I really don't understand my mistake. I also check if my class Vertex was correct, and it is working well.

public class Vertex implements Comparable<Vertex> {

private int label;

public Vertex(int label) {
    this.label = label;
}

public String toString() {
    return this.label + "";
}

public int compareTo(Vertex o) {
    return this.label == o.label ? 1 : 0;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) return false;

    if( ! (obj instanceof Vertex) ) return false;

    Vertex other = (Vertex) obj;

    return this.label == other.label;
}

@Override
public int hashCode() {
    return label < 0 ? 0 : label;
}

}

I edited my Vertex class and addded hashcode() and equals() but it still doesn't work.

Can you help me to find my mistake please ? Thanks by advance !

Upvotes: 0

Views: 264

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308021

Your compareTo method is wrong. Take a look at its specification:

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.

Since you only ever return the values 1 and 0, this condition can not hold.

In general a comparable must always support all three cases:

  • this is less than the argument: return a negative integer (usually -1)
  • this is sorted the same as the argument: return 0
  • this is greater than the argument: return a positive integer (usually 1)

If your code doesn't have those three cases, it can't be correct.

Since you basically want to sort according to label, the simplest implementation would be to delegate to Integer.compare:

public int compareTo(Vertex o) {
    return Integer.compare(this.label, o.label);
}

Upvotes: 1

Related Questions