Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is the comparator used instead of the equals() in Collections?
    text
    copied!<p>There is a java bean Car that might contains two values: model and price.</p> <p>Now suppose I override equals() and hashcode() checking only for model in that way:</p> <pre><code>public boolean equals(Object o) { return this.model.equals(o.model); } public int hashCode() { return model.hashCode(); } </code></pre> <p>This permit me to check if an arraylist already contain an item Car of the same model (and doesn't matter the price), in that way:</p> <pre><code>List&lt;Car&gt; car = new ArrayList&lt;Car&gt;(); car.add(new Car("carA",100f)); car.add(new Car("carB",101f)); car.add(new Car("carC",110f)); System.out.println(a.contains(new Car("carB",111f))); </code></pre> <p>It returns TRUE. That's fine, because the car already exist!</p> <p>But now I decide that the ArrayList is not good, because I want to maintain the items ordered, so I substitute it with a TreeSet in this way:</p> <pre><code>Set&lt;Car&gt; car = new TreeSet&lt;Car&gt;(new Comparator&lt;Car&gt;() { @Override public int compare(Car car1, Car car2) { int compPrice = - Float.compare(car1.getPrice(), car2.getPrice()); if (compPrice &gt; 0 || compPrice &lt; 0) return compPrice; else return car1.getModel().compareTo(car2.getModel()); </code></pre> <p>}});</p> <pre><code>car.add(new Car("carA",100f)); car.add(new Car("carB",101f)); car.add(new Car("carC",110f)); System.out.println(a.contains(new Car("carB",111f))); </code></pre> <p>But now there is a problem, it return FALSE... why?</p> <p>It seems that when I invoke contains() using an arrayList the method equals() is invoked. But it seems that when I invoke contains() using a TreeSet with a comparator, the comparator is used instead.</p> <p>Why does that happen?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload