compare ()와 compareTo ()의 차이점은 무엇입니까?
Java compare()
와 compareTo()
메소드 의 차이점은 무엇입니까 ? 그 방법들이 같은 대답을하나요?
에서 JavaNotes :
a.compareTo(b)
:
Comparable 인터페이스 : 값을 비교하고 값이보다 작거나 같거나 큰지 여부를 나타내는 int를 반환합니다.
클래스 객체에 자연스러운 순서 가있는 경우Comparable<T>
인터페이스를 구현 하고이 메서드를 정의합니다. 자연스러운 순서가 구현 된 모든 Java 클래스Comparable<T>
-예 :String
, 래퍼 클래스 ,BigInteger
compare(a, b)
:
비교기 인터페이스 : 두 개체의 값을 비교합니다. 이는 일부로서 구현되는Comparator<T>
인터페이스 및 일반적인 사용과 같은 방법에 전달이를 구현하는 하나 개 이상의 작은 유틸리티 클래스를 정의하는sort()
거나 같은 데이터 구조를 정렬하여 사용TreeMap
하고TreeSet
. 다음에 대한 Comparator 개체를 만들 수 있습니다.- 다중 비교 . 무언가를 정렬하는 여러 가지 방법을 제공합니다. 예를 들어 Person 클래스를 이름, ID, 나이, 키로 정렬 할 수 있습니다
sort()
. 메소드 에 전달할 이들 각각에 대해 Comparator를 정의합니다 . - 시스템 클래스 제어 할 수없는 클래스에 대한 비교 방법을 제공합니다. 예를 들어 길이를 기준으로 비교하는 문자열 비교기를 정의 할 수 있습니다.
- 전략 패턴 매개 변수로 전달할 수있는 객체로 알고리즘을 표현하고 데이터 구조에 저장하는 등의 상황 인 전략 패턴 을 구현합니다.
- 다중 비교 . 무언가를 정렬하는 여러 가지 방법을 제공합니다. 예를 들어 Person 클래스를 이름, ID, 나이, 키로 정렬 할 수 있습니다
클래스 객체에 하나의 자연 정렬 순서가있는 경우 compare ()가 필요하지 않을 수 있습니다.
http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html의 요약
비교
가능 비교 가능한 객체는 자신을 다른 객체와 비교할 수 있습니다.
비교기
비교기 객체는 두 개의 다른 물체를 비교할 수있다. 클래스가 인스턴스를 비교하지 않고 다른 클래스의 인스턴스를 비교합니다.
사용 사례 컨텍스트 :
비슷한 인터페이스
는 방법과 동일 ==
및 !=
사업자 평등 / 불평등에 대한 테스트를하지만, 상대 값을 테스트 할 수있는 방법을 제공하지 않습니다 .
일부 클래스 (예 : String 및 자연스러운 순서를 가진 기타 클래스) Comparable<T>
는 compareTo()
메서드 를 정의하는 인터페이스를 구현합니다 . 또는 메소드 와 함께 사용하려는 경우 클래스에서
구현 Comparable<T>
하고 싶을 것입니다 .Collections.sort()
Arrays.sort()
Comparator 개체 정의
Comparators를 만들어 모든 클래스에 대해 임의의 방식 으로 정렬 할 수 있습니다 .
예를 들어, String
클래스는 CASE_INSENSITIVE_ORDER
comparator를 정의합니다 .
두 접근 방식의 차이점은 다음과 같은 개념에 연결될 수 있습니다.
Ordered Collection :
컬렉션이 주문되면 특정 (무작위 Hashtable
가 아닌 ) 순서로 컬렉션에서 반복 할 수 있습니다 (a 는 주문되지 않음).
자연스러운 순서를 가진 컬렉션 은 단순히 정렬되는 것이 아니라 정렬 됩니다. 자연스러운 순서를 정의하는 것은 어려울 수 있습니다! ( 자연스러운 문자열 순서대로 ).
코멘트 에서 HaveAGuess 가 지적한 또 다른 차이점 은 다음과 같습니다.
Comparable
구현 중이며 인터페이스에서 보이지 않으므로 정렬 할 때 어떤 일이 발생할지 실제로 알 수 없습니다.Comparator
주문이 잘 정의 될 것이라는 확신을줍니다.
compareTo()
Comparable
인터페이스 에서 가져온 것 입니다.
compare()
Comparator
인터페이스 에서 가져온 것 입니다.
두 방법 모두 동일한 작업을 수행하지만 각 인터페이스는 약간 다른 컨텍스트에서 사용됩니다.
에 Comparable 인터페이스를 구현하는 클래스의 객체에 자연 순서를 부과하는 데 사용됩니다. 이 compareTo()
방법을 자연 비교 방법이라고합니다. 비교기 인터페이스를 구현하는 클래스의 오브젝트에 전체 순서를 부과하는 데 사용됩니다. 자세한 내용은 각 인터페이스를 사용하는 정확한시기에 대한 링크를 참조하십시오.
유사점 :
둘 다 두 개체를 비교하는 사용자 지정 방법입니다.
둘 다 int
두 개체 간의 관계를 설명하는 반환 합니다.
차이점 : 이 방법 compare()
은 Comparator
인터페이스 를 구현하는 경우 구현해야하는 방법입니다 . 두 개체를 메서드에 전달할 수 있으며 int
해당 관계를 설명하는 반환합니다 .
Comparator comp = new MyComparator();
int result = comp.compare(object1, object2);
이 메서드 compareTo()
는 Comparable
인터페이스 를 구현하는 경우 구현해야하는 메서드입니다 . 개체를 유사한 유형의 개체와 비교할 수 있습니다.
String s = "hi";
int result = s.compareTo("bye");
요약 :
기본적으로 두 가지 방법으로 사물을 비교합니다.
방법이 같은 답을 줄 필요는 없습니다. 그것은 당신이 그들을 부르는 객체 / 클래스에 달려 있습니다.
어떤 단계에서 비교하고 싶은 자신의 클래스를 구현하는 경우 Comparable 인터페이스를 구현하고 그에 따라 compareTo () 메서드를 구현할 수 있습니다.
Comparable 인터페이스를 구현하지 않는 API의 일부 클래스를 사용하고 있지만 여전히 비교하고 싶은 경우. 즉 정렬을 위해. Comparator 인터페이스를 구현하는 고유 한 클래스를 만들고 compare () 메서드에서 논리를 구현할 수 있습니다.
비교 가능한 인터페이스에는 compareTo(obj)
하나의 인수 만 취하고 동일한 클래스의 다른 인스턴스 또는 객체와 자신을 비교 하는 메서드가 포함되어 있습니다 .
Comparator 인터페이스에는 compare(obj1,obj2)
두 개의 인수를 사용 하는 메서드가 포함되어 있으며 동일하거나 다른 클래스의 두 개체 값을 비교합니다.
compareTo(T object)
comes from the java.lang.Comparable interface, implemented to compare this object with another to give a negative int value for this object being less than, 0 for equals, or positive value for greater than the other. This is the more convenient compare method, but must be implemented in every class you want to compare.
compare(T obj1, T obj2)
comes from the java.util.Comparator interface, implemented in a separate class that compares another class's objects to give a negative int value for the first object being less than, 0 for equals, or positive value for greater than the second object. It is needed when you cannot make a class implement compareTo() because it is not modifiable. It is also used when you want different ways to compare objects, not just one (such as by name or age).
Using Comparator, we can have n number of comparison logic written for a class.
E.g.
For a Car Class
We can have a Comparator class to compare based on car model number. We can also have a Comparator class to compare based on car model year.
Car Class
public class Car {
int modelNo;
int modelYear;
public int getModelNo() {
return modelNo;
}
public void setModelNo(int modelNo) {
this.modelNo = modelNo;
}
public int getModelYear() {
return modelYear;
}
public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}
}
Comparator #1 based on Model No
public class CarModelNoCompartor implements Comparator<Car>{
public int compare(Car o1, Car o2) {
return o1.getModelNo() - o2.getModelNo();
}
}
Comparator #2 based on Model Year
public class CarModelYearComparator implements Comparator<Car> {
public int compare(Car o1, Car o2) {
return o1.getModelYear() - o2.getModelYear();
}
}
But this is not possible with the case of Comparable interface.
In case of Comparable interface, we can have only one logic in compareTo() method.
compareTo()
is called on one object, to compare it to another object. compare()
is called on some object to compare two other objects.
The difference is where the logic that does actual comparison is defined.
The relationship of the object having this method and its collaborators is different.
compareTo()
is a method of the interface Comparable, so it is used to compare THIS instance to another one.
compare()
is a method of the interface Comparator, so it is used to compare two different instances of another class with each other.
If you will, implementing Comparable
means that instances of the class can be easily compared.
Implementing Comparator
means, that instances are suited to compare different objects (of other classes).
The main difference is in the use of the interfaces:
Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.
When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.
When you want to write a Util class which compares two other classes you can implement the Comparator class.
Employee Table
Name, DoB, Salary
Tomas , 2/10/1982, 300
Daniel , 3/11/1990, 400
Kwame , 2/10/1998, 520
The Comparable interface allows you to sort a list of objects eg Employees with reference to one primary field – for instance, you could sort by name or by salary with the CompareTo() method
emp1.getName().compareTo(emp2.getName())
A more flexible interface for such requirements is provided by the Comparator interface, whose only method is compare()
public interface Comparator<Employee> {
int compare(Employee obj1, Employee obj2);
}
Sample code
public class NameComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
// some conditions here
return e1.getName().compareTo(e2.getName()); // returns 1 since (T)omas > (D)an
return e1.getSalary().compareTo(e2.getSalary()); // returns -1 since 400 > 300
}
}
One more point:
compareTo()
is from theComparable
interface andcompare()
is from theComparator
interface.Comparable
is used to define a default ordering for objects within a class whileComparator
is used to define a custom ordering to be passed to a method.
There is a technical aspect that should be emphasized, too. Say you need comparison behavior parameterization from a client class, and you are wondering whether to use Comparable
or Comparator
for a method like this:
class Pokemon {
int healthPoints;
int attackDamage;
public void battle (Comparable<Pokemon> comparable, Pokemon opponent) {
if (comparable.compareTo(opponent) > 0) { //comparable needs to, but cannot, access this.healthPoints for example
System.out.println("battle won");
} else {
System.out.println("battle lost");
}
}
}
comparable
would a lambda or an object, and there is no way for comparable
to access the fields of this
Pokemon. (In a lambda, this
refers to the outer class instance in the lambda's scope, as defined in the program text.) So this doesn't fly, and we have to use a Comparator
with two arguments.
Use Comparable interface for sorting on the basis of more than one value like age,name,dept_name... For one value use Comparator interface
Important Answar
String name;
int roll;
public int compare(Object obj1,Object obj2) { // For Comparator interface
return obj1.compareTo(obj1);
}
public int compareTo(Object obj1) { // For Comparable Interface
return obj1.compareTo(obj);
}
Here in return obj1.compareTo(obj1)
or return obj1.compareTo(obj)
statement only take Object; primitive is not allowed. For Example
name.compareTo(obj1.getName()) // Correct Statement.
But
roll.compareTo(obj1.getRoll())
// Wrong Statement Compile Time Error Because roll
// is not an Object Type, it is primitive type.
name is String Object so it worked. If you want to sort roll number of student than use below code.
public int compareTo(Object obj1) { // For Comparable Interface
Student s = (Student) obj1;
return rollno - s.getRollno();
}
or
public int compare(Object obj1,Object obj2) { // For Comparator interface
Student s1 = (Student) obj1;
Student s2 = (Student) obj2;
return s1.getRollno() - s2.getRollno();
}
참고URL : https://stackoverflow.com/questions/420223/what-is-the-difference-between-compare-and-compareto
'developer tip' 카테고리의 다른 글
클래스에 개체 구성원이 없습니다. (0) | 2020.08.14 |
---|---|
에뮬레이션과 시뮬레이션의 차이점은 무엇입니까? (0) | 2020.08.14 |
루비 연산자 "= ~" (0) | 2020.08.13 |
Java EE 개발자 용 Eclipse를 업그레이드하는 방법은 무엇입니까? (0) | 2020.08.13 |
virtualenvwrapper로 환경 이름 바꾸기 (0) | 2020.08.13 |