Comparator: Equals function

In fact, I turn to one of the lessons that mentioned that when we need to implement the comparator interface, we can override the equals method (However, it does not need to be redefined).

So just a better understanding.

i overrides the method below

Test.java

 import java.util.TreeSet;

public class Test
{
    public static void main(String[] args)
    {
        TreeSet t = new TreeSet(new MyComparator());
        t.add(1);
        t.add(1);
        t.add(2);
        System.out.println(t);
    }
}

MyComparator.java

import java.util.Comparator;

public class MyComparator
    implements Comparator
{
    @Override
    public int compare(Object o1, Object o2)
    {
        Integer i1 = (Integer) o1;
        Integer i2 = (Integer) o2;
        return i1.compareTo(i2);
    }

    @Override
    public boolean equals(Object o1)
    {
        return false;
    }
}

for another scenario

import java.util.Comparator;

public class MyComparator
    implements Comparator
{
    @Override
    public int compare(Object o1, Object o2)
    {
        Integer i1 = (Integer) o1;
        Integer i2 = (Integer) o2;
        return i1.compareTo(i2);
    }

    @Override
    public boolean equals(Object o1)
    {
        return true;
    }
}

Now, regardless of the fact that I return both true and false from the equals method, it returns the same treeet value. if someone can clear the concept of functional equals, please

+5
source share
6 answers

equals() Comparator , , . , . . - , equals() . , .

+7

equals() Comparator Comparator , Java- , compareTo() equals() .

Java == / , . :

String apple1 = new String("apple");
String apple2 = new String("apple"); 
System.out.println(apple1.equals(apple2)); // true

StringBuilder app1 = new StringBuilder("apple"); 
StringBuilder app2 = new StringBuilder("apple"); 
System.out.println(app1.equals(app2));   // false

, . ? , String equals(), , . , StringBuilder equals(), equals(), Object. , () Object, , .

, , Java, equals(), , , equals(), Object equals()

, , : Apple

public class Apple  {

    private int weight;
    private int cost;
    private String color;

, , ? , , - ? equals, .

Apple , , "Apple", . , , , , , , , .

    @Override
    public boolean equals(Object obj) {
        if ( !(obj instanceof Apple)) return false;    
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Apple other = (Apple) obj;
        if (cost != other.cost and weight != other.weight )
            return false;
        return true;
    }

, equals(). Java equals() , . , , .

equals() - , equals(), hashCode(). , hashcode Java, .

Hashcode - , . , (, , ) , . , , , ( ), , , , , hashCode(). hashCode() , equals(). :

-, hashCode() . , hascode() , . , Apple , .. , hashcode(), .

, , equals() true, hashCode() . equals() false , hashCode() . ? ? hashCode() , .

Comparator - , , .

, , Apple : weight price TreeSet.

public class Apple  {

    private int weight;
    private int cost;

, , - weight price? ?

Comparator Comparable . .

  public class Apple {

    private int weight;
    private int cost;

  public static void main(String[] args) {
    Apple redApple = new Apple();
    redApple.setCost(10);
    redApple.setWeight(2);

    Apple greenApple = new Apple();
    greenApple.setCost(12);
    greenApple.setWeight(3);

    Set<Apple> apples = new TreeSet<>();
    apples.add(redApple);
    apples.add(greenApple);

    System.out.println(apples);
   } 

    public int getWeight() {
       return weight;
    }

   public void setWeight(int weight) {
       this.weight = weight;
    }

   public int getCost() {
       return cost;
   }

   public void setCost(int cost) {
     this.cost = cost;
    }

   @Override
   public String toString() {
       return "Apple [weight=" + weight + ", cost=" + cost + "]";
    }
}

, RuntimeError: Apple cannot be cast to java.lang.Comparable, , . : Comparable

  public class Apple implements Comparable<Apple> {

compareTo

 @Override
    public int compareTo(Object obj) {

        int cost = ((Apple) obj).getCost();
        return this.getCost() - cost; // sorting in ascending order.

        // change to this to sort in Descending order
        // return cost - this.getCost();
    }

:

[Apple [weight=2, cost=10], Apple [weight=3, cost=12]]

.

, Apple, Comparable.

Comparator .

implements Comparable, ,

public class Apple {

@Override
public String toString() {
    return "Apple [weight=" + weight + ", cost=" + cost + "]";
}

:

  public class AppleComparator implements Comparator<Apple> {

        @Override
        public int compare(Apple app1, Apple app2) {
            return app1.getCost() - app2.getCost();
        }

}

Comparator ,

Set<Apple> apples = new TreeSet<>(new AppleComparator());

, . Comparator, Comparable, , TreeSet.

: Comparator equals(). Comparable (compareTo()) equals().

- Apple , Comparable, . compareTo() 0, , equals() true, .

, compareTo(), iff x.equals(y) , x.compareTo(y) 0. , Comparable , Java- , compareTo() equals() .

compareTo(), :

public class Apple implements Comparable<Apple> { 

private int weight;
private int cost;
private String color;

public boolean equals(Object obj) {
   if(!(obj instanceof Apple)) { 
      return false;
  }
   Apple other = (Apple) obj; 
    return this.weight == other.weight;
  }

public int compareTo(Apple obj) {
    return this.cost.compareTo(obj.cost); }
 }

Apple , . . compareTo() 0 Apple , , compareTo() equals().

+2

equals(), , MyComparator class, , 2 Mycomparator;)

, , int, , compare() , , sorting Treeset, equals ' t

99% override equals , implements Comparator, compare , , , Comparator .

+1

, Comparator equals(). interfaces Comparable Comparator , , collection, sorting purpose, .

package snippet;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

class Person {

    private int id;
    private String name;
    private String code;
    private double salary;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public boolean equals(Object obj) {         
        if(obj != null && (obj instanceof Person)) {
            Person other = (Person) obj;
            return this.code.equals(other.getCode());
        }
        return false;
    }
    public Person(int id, String name, String code, double salary) {
        super();
        this.id = id;
        this.name = name;
        this.code = code;
        this.salary = salary;
    }
}

public class EqualsMethodImpl
{
    public static void main(String[] args) {
        Set<Person> set = new TreeSet<Person>();
        Person p1 = new Person(1, "Sam", "M-1-SAM-50", 50000.00);
        Person p2 = new Person(2, "Diaz", "M-1-SAM-35", 35000.00);
        Person p3 = new Person(3, "Remy", "M-1-SAM-100", 100000.00);
        Person p4 = new Person(4, "Cesar", "M-1-SAM-80", 80000.00);
        Person p5 = new Person(5, "Rino", "M-1-SAM-5", 5000.00);

        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p4);
        set.add(p5);

        printPersons(set);
    }

    private static void printPersons(Set<Person> set) {
        System.out.println("Id\tName\tCode\t\tSalary");
        Iterator<Person> perItr = set.iterator();       
        while(perItr.hasNext()) {
            Person p = perItr.next();
            System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getCode()+"\t"+p.getSalary());
        }
    }
}

, ClasCastException set.add(p1);, , TreeSet , Peron . , interfaces, Comparable Comparator.

Person

public int compareTo(Person other) {
    Double person1Salary = this.getSalary();
    Double person2Salary = other.getSalary();
    return person1Salary.compareTo(person2Salary);
}

Classable Person implements Comparable<Person>

, , . , Set, ( ).

Wrapper, Byte, Short, Integer, Long, Float, Double , String, Comaparable .

, equals, , equals, Object, . Person, equals, ,

Person p1 = new Person(1, "Sam", "M-1-SAM-50", 50000.00);
Person p2 = new Person(1, "Sam", "M-1-SAM-50", 50000.00);
System.out.println(p1.equals(p2));

false, , , , . , equals(), Person Person code. System.out.println(p1.equals(p2)); true, . equals() . , .

+1

equals , .. equals , ComparatorA ComparatorB Identical, , .

0

, . , , , ( , ) ( , , ). MyComparator Comparator, , , , , . (, , ), , , - , Integer, , ClassCastException. , Comparator<Integer>, , compare compare(Integer, Integer) compare(Object, Object), , , Integer, , .

, , , Comparator Comparable. A Comparable , - " ", Java. , , (Double.NaN - , ). , Integer Comparable<Integer> ( Comparable<Number>, ). , , . . Person Comparable<Person>, TreeSet<Person>, , . , , , . , Comparator<Person>. , , .., Comparator<Person>, a Person .

, - , Comparable, Comparator, Comparable.

, javadocs , " ", "" equals(Object) , , Comparable Comparator. , ( Comparator ) equals(Object), , " ", equals(Object) Comparator, ( Comparator s).

An example of natural ordering that does not match peers is the class example BigDecimal. Two BigDecimal, representing 2.0and 2.00, will not be equal according to BigDecimal.equals(Object), but they will be considered equal by their natural ordering (i.e., On compareTo(BigDecimal)).

-1
source

Source: https://habr.com/ru/post/1682597/


All Articles