Java compareto не равно

Comparable и Comparator

Два новых интерфейса java.lang.Comparable и java.util.Comparator были добавлены в версии Java 5. Использование данных интерфейcов в своих приложениях позволяет упорядочивать (сортировать) данные.

Интерфейс Comparable

В интерфейсе Comparable объявлен только один метод compareTo (Object obj), предназначенный для упорядочивания объектов класса. Данный метод удобно использовать для сортировки списков или массивов объектов.

Метод compareTo (Object obj) сравнивает вызываемый объект с obj. В отличие от метода equals, который возвращает true или false, compareTo возвращает:

  • 0, если значения равны;
  • Отрицательное значение (обычно -1), если вызываемый объект меньше obj;
  • Положительное значение (обычно +1), если вызываемый объект больше obj.

Если типы объектов не совместимы при сравнении, то compareTo (Object obj) может вызвать исключение ClassCastException. Необходимо помнить, что аргумент метода compareTo имеет тип сравниваемого объекта класса.

Обычные классы Byte, Short, Integer, Long, Double, Float, Character, String уже реализуют интерфейс Comparable.

Пример реализации интерфейса Comparable

package test; import java.util.TreeSet; class Compare implements Comparable  < String str; int num; String TEMPLATE = "num = %d, str = '%s'"; Compare(String str, int num) < this.str = str; this.num = num; >@Override public int compareTo(Object obj) < Compare entry = (Compare) obj; int result = str.compareTo(entry.str); if(result != 0) return result; result = num - entry.num; if(result != 0) return (int) result / Math.abs( result ); return 0; >@Override public String toString() < return String.format(TEMPLATE, num, str); >> public class Example < public static void main(String[] args) < TreeSetdata = new TreeSet(); data.add(new Compare("Начальная школа" , 234)); data.add(new Compare("Начальная школа" , 132)); data.add(new Compare("Средняя школа" , 357)); data.add(new Compare("Высшая школа" , 246)); data.add(new Compare("Музыкальная школа", 789)); for (Compare e : data) System.out.println(e.toString()); > >

Результат выполнения программы:

num = 246, str = 'Высшая школа' num = 789, str = 'Музыкальная школа' num = 132, str = 'Начальная школа' num = 234, str = 'Начальная школа' num = 357, str = 'Средняя школа'

В примере значения сортируются сначала по полю str (по алфавиту), а затем по num в методе compareTo. Это хорошо видно по двум строкам с одинаковыми значения str и различными num. Чтобы изменить порядок сортировки значения str (в обратном порядке), необходимо внести небольшие изменения в метод compareTo.

@Override public int compareTo(Object obj) < int result = ((Comp)obj).str.compareTo(str); if(result != 0) return result; result = entry.number - number; if(result != 0) < return (int) result / Math.abs(result); return 0; >

Интерфейс Comparator : compare, compareTo

В интерфейсе Comparator объявлен метод compare (Object obj1, Object obj2), который позволяет сравнивать между собой два объекта. На выходе метод возвращает значение 0, если объекты равны, положительное значение или отрицательное значение, если объекты не тождественны.

Читайте также:  Jino как изменить версию php

Метод может вызвать исключение ClassCastException, если типы объектов не совместимы при сравнении. Простой пример реализации интерфейса Comparator:

package test; import java.util.TreeSet; import java.util.Iterator; import java.util.Comparator; class Compare implements Comparator  < @Override public int compare(String obj1, String obj2) < return obj1.compareTo(obj2); >> public class Example < public static void main(String[] args) < TreeSetdata = new TreeSet(); data.add(new String("Змей Горыныч" )); data.add(new String("Баба Яга" )); data.add(new String("Илья Муромец" )); data.add(new String("Алеша Попович" )); data.add(new String("Соловей Разбойник")); Iterator i = data.iterator(); while(i.hasNext()) System.out.println(i.next()); > >

Результат выполнения программы:

Алеша Попович Баба Яга Змей Горыныч Илья Муромец Соловей Разбойник

Усложним пример, и реализуем несколько видов сортировки. Для этого создадим класс Product с полями name, price и quantity.

class Product < private String name; private float price; private float quantity; public Product (String name, float price, float quantity) < this.name = name; this.price = price; this.quantity = quantity; >public String getName() < return name; >public void setName(String name) < this.name = name; >public float getPrice() < return price; >public void setPrice(float price) < this.price = price; >public float getQuantity() < return quantity; >public void setQuantity(float quantity) < this.quantity = quantity; >@Override public String toString() < return "Наименование '" + name + "', цена - " + String.valueOf (price) + ", количество - " + String.valueOf (quantity); >>

Создадим два класса (SortedByName, SortedByPrice), реализующих интерфейс Comparator для сортировки объектов по названию и по цене :

// сортировка по названию class SortedByName implements Comparator  < public int compare(Product obj1, Product obj2) < String str1 = obj1.getName(); String str2 = obj2.getName(); return str1.compareTo(str2); >> // сортировка по цене class SortedByPrice implements Comparator  < public int compare(Product obj1, Product obj2) < float price1 = obj1.getPrice(); float price2 = obj2.getPrice(); if (price1 >price2) < return 1; >else if (price1 < price2) < return -1; >else < return 0; >> >

Пример использования Arrays.sort :

Результат выполнения программы:

~~~~~ без сортировки Наименование 'Молоко', цена - 35.56, количество - 900.0 Наименование 'Кофе', цена - 199.5, количество - 90.0 Наименование 'Чай', цена - 78.5, количество - 150.0 ~~~ сортировка по цене Наименование 'Молоко', цена - 35.56, количество - 900.0 Наименование 'Чай', цена - 78.5, количество - 150.0 Наименование 'Кофе', цена - 199.5, количество - 90.0 ~~~ сортировка по названию Наименование 'Кофе', цена - 199.5, количество - 90.0 Наименование 'Молоко', цена - 35.56, количество - 900.0 Наименование 'Чай', цена - 78.5, количество - 150.0

Для сортировки объектов были реализованы два независимых компаратора по наименованию и по цене (SortedByName и SortedByPrice). Сортировка выполняется с помощью класса Arrays, у которого есть метод sort. Данный метод в качестве второго аргумента принимает тип компаратора.

Arrays.sort(T[] arg1, Comparator arg2);

Можно использовать также метод sort класса Collections, который в качестве первого входного аргумента принимает список объектов:

Collections.sort(List arg1, Comparator arg2);

Отличие интерфейсов Comparator и Comparable

Интерфейс Comparable используется только для сравнения объектов класса, в котором данный интерфейс реализован. Т.е. interface Comparable определяет логику сравнения объекта определенного ссылочного типа внутри своей реализации (по правилам разработчика).

Comparator представляет отдельную реализацию и ее можно использовать многократно и с различными классами. Т.е. interface Comparator позволяет создавать объекты, которые будут управлять процессом сравнения (например при сортировках).

Источник

Java compareto не равно

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort ). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator. The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false. It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave «strangely» when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method. For example, if one adds two keys a and b such that (!a.equals(b) && a.compareTo(b) == 0) to a sorted set that does not use an explicit comparator, the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set’s perspective. Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals. One exception is java.math.BigDecimal, whose natural ordering equates BigDecimal objects with equal values and different precisions (such as 4.0 and 4.00). For the mathematically inclined, the relation that defines the natural ordering on a given class C is:

It follows immediately from the contract for compareTo that the quotient is an equivalence relation on C, and that the natural ordering is a total order on C. When we say that a class’s natural ordering is consistent with equals, we mean that the quotient for the natural ordering is the equivalence relation defined by the class’s equals(Object) method:

Method Summary

Method Detail

compareTo

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.) The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0. Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z. It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is «Note: this class has a natural ordering that is inconsistent with equals.» In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Interface Comparable

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort ). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C . Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false .

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave «strangely» when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

For example, if one adds two keys a and b such that (!a.equals(b) && a.compareTo(b) == 0) to a sorted set that does not use an explicit comparator, the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set’s perspective.

Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals. One exception is BigDecimal , whose natural ordering equates BigDecimal objects with equal numerical values and different representations (such as 4.0 and 4.00). For BigDecimal.equals() to return true, the representation and numerical value of the two BigDecimal objects must be the same.

For the mathematically inclined, the relation that defines the natural ordering on a given class C is:

It follows immediately from the contract for compareTo that the quotient is an equivalence relation on C , and that the natural ordering is a total order on C . When we say that a class’s natural ordering is consistent with equals, we mean that the quotient for the natural ordering is the equivalence relation defined by the class’s equals(Object) method:

In other words, when a class’s natural ordering is consistent with equals, the equivalence classes defined by the equivalence relation of the equals method and the equivalence classes defined by the quotient of the compareTo method are the same.

This interface is a member of the Java Collections Framework.

Источник

Оцените статью