programing

Java 클래스가 동등한 기능을 구현해야 하는 이유는 무엇입니까?

yoursource 2022. 10. 23. 19:54
반응형

Java 클래스가 동등한 기능을 구현해야 하는 이유는 무엇입니까?

왜 자바인가?Comparable왜 다른 사람이 실장했을까요?Comparable수업시간에?유사한 기능을 구현해야 하는 실제 예는 무엇입니까?

여기 실제 샘플이 있습니다.주의:String실장하다Comparable.

class Author implements Comparable<Author>{
    String firstName;
    String lastName;

    @Override
    public int compareTo(Author other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than 
        // other and 0 if they are supposed to be equal
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;
    }
}

나중에...

/**
 * List the authors. Sort them by name so it will look good.
 */
public List<Author> listAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    Collections.sort(authors);
    return authors;
}

/**
 * List unique authors. Sort them by name so it will look good.
 */
public SortedSet<Author> listUniqueAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return new TreeSet<Author>(authors);
}

Comparible은 자연스러운 순서를 정의합니다.즉, 하나의 개체가 "보다 작음" 또는 "보다 큼"으로 간주될 때 정의하는 것입니다.

예를 들어, 정수가 여러 개 있고 그것들을 정렬하려고 합니다.그건 꽤 쉬워요, 그냥 분류된 컬렉션에 넣어요, 그렇죠?

TreeSet<Integer> m = new TreeSet<Integer>(); 
m.add(1);
m.add(3);
m.add(2);
for (Integer i : m)
... // values will be sorted

그러나 이제 정렬은 가능하지만 정의되지 않은 사용자 지정 개체가 있다고 가정합니다.예를 들어, 인구밀도의 우편번호로 지역을 나타내는 데이터가 있는데, 밀도로 정렬하려고 합니다.

public class District {
  String zipcode; 
  Double populationDensity;
}

이러한 개체를 정렬하는 가장 쉬운 방법은 Comparable을 구현하여 자연스러운 순서로 정의하는 것입니다. 즉, 이러한 개체의 순서를 정의하는 표준 방법이 있습니다.

public class District implements Comparable<District>{
  String zipcode; 
  Double populationDensity;
  public int compareTo(District other)
  {
    return populationDensity.compareTo(other.populationDensity);
  }
}

비교기를 정의하여 동일한 작업을 수행할 수 있습니다.차이점은 비교기가 객체 외부의 순서 로직을 정의한다는 것입니다.다른 프로세스에서는 같은 오브젝트를 우편번호로 주문해야 할 수도 있습니다.이 경우 오더는 오브젝트의 속성이 아니거나 오브젝트의 자연스러운 오더와 다를 수 있습니다.외부 비교기를 사용하여 예를 들어 정수의 알파벳 값을 기준으로 정수를 정렬하여 정수에 대한 사용자 정의 순서를 정의할 수 있습니다.

기본적으로 주문 논리는 어딘가에 존재해야 합니다.이것은, 다음과 같은 경우가 있습니다.

  • 오브젝트 자체에서 자연스럽게 비교 가능한 경우(Comparible - 예를 들어 정수)

  • 위의 예시와 같이 외부 비교기에 공급됩니다.

javadoc에서 인용.

이 인터페이스는 이 인터페이스를 구현하는 각 클래스의 오브젝트에 토탈 순서를 부과합니다.이 순서를 클래스의 자연스러운 순서라고 하고 클래스의 compareTo 메서드를 자연스러운 비교 메서드라고 합니다.

이 인터페이스를 구현하는 개체 목록(및 배열)은 컬렉션별로 자동으로 정렬할 수 있습니다.정렬(및 Arrays.sort)을 수행합니다.이 인터페이스를 구현하는 오브젝트는 비교기를 지정할 필요 없이 정렬된 맵의 키 또는 정렬된 세트의 요소로 사용할 수 있습니다.

편집: ..중요한 비트를 굵게 했습니다.

가 실장하고 것Comparable그 클래스에서 두 개체를 가져와 비교할 수 있습니다.오브젝트를 순서대로 유지하는 특정 컬렉션(컬렉션 내의 정렬 함수)과 같은 클래스는 비교 가능한 것에 의존합니다(정렬하려면 어떤 오브젝트가 가장 큰지 알아야 합니다).

위의 대부분의 예는 compareTo 함수의 기존 동등한 객체를 재사용하는 방법을 보여줍니다.동일한 클래스의 두 개체를 비교하려는 경우 가격별로 정렬할 AirlineTicket 개체(낮은 것이 1위)와 경유지 수(낮은 것이 1위)를 차례로 비교하려면 다음을 수행합니다.

class AirlineTicket implements Comparable<Cost>
{
    public double cost;
    public int stopovers;
    public AirlineTicket(double cost, int stopovers)
    {
        this.cost = cost; this.stopovers = stopovers ;
    }

    public int compareTo(Cost o)
    {
        if(this.cost != o.cost)
          return Double.compare(this.cost, o.cost); //sorting in ascending order. 
        if(this.stopovers != o.stopovers)
          return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
        return 0;            
    }
}

여러 필드 비교를 구현하기 위한 간단한 방법은 Guava의 Comparison Chain을 사용하는 입니다.

   public int compareTo(Foo that) {
     return ComparisonChain.start()
         .compare(lastName, that.lastName)
         .compare(firstName, that.firstName)
         .compare(zipCode, that.zipCode)
         .result();
   }

대신

  public int compareTo(Person other) {
    int cmp = lastName.compareTo(other.lastName);
    if (cmp != 0) {
      return cmp;
    }
    cmp = firstName.compareTo(other.firstName);
    if (cmp != 0) {
      return cmp;
    }
    return Integer.compare(zipCode, other.zipCode);
  }
}

Comparible(비교적)으로 예를 할 수 에 이 .compareTo인스턴스를 비교하는 방법(아트리뷰트)을 알기 위해서입니다.

Dog 링크:

package test;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Dog d1 = new Dog("brutus");
        Dog d2 = new Dog("medor");
        Dog d3 = new Dog("ara");
        Dog[] dogs = new Dog[3];
        dogs[0] = d1;
        dogs[1] = d2;
        dogs[2] = d3;

        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * brutus
         * medor
         * ara
         */

        Arrays.sort(dogs, Dog.NameComparator);
        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * ara
         * medor
         * brutus
         */

    }
}

Main 링크:

package test;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Dog d1 = new Dog("brutus");
        Dog d2 = new Dog("medor");
        Dog d3 = new Dog("ara");
        Dog[] dogs = new Dog[3];
        dogs[0] = d1;
        dogs[1] = d2;
        dogs[2] = d3;

        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * brutus
         * medor
         * ara
         */

        Arrays.sort(dogs, Dog.NameComparator);
        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * ara
         * medor
         * brutus
         */

    }
}

다음은 Java에서 동등한 기능을 사용하는 좋은 예입니다.

http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2

예를 들어 정렬된 컬렉션 또는 맵을 원하는 경우

왜 '나'나 '나'나 '나를하면 안 돼요?compareTo()같은 인터페이스를 실장하지 않은 메서드.를 들어 클래스 " " " " 입니다.City 정의로 name ★★★★★★★★★★★★★★★★★」temperature ★★★★★★★★★★★★★★★★★」

public int compareTo(City theOther)
{
    if (this.temperature < theOther.temperature)
        return -1;
    else if (this.temperature > theOther.temperature)
        return 1;
    else
        return 0;
}

「 」를 Comparable에서는 메서드인터페이스인 'Method Interface'를 .compareTo() 사물을 는 예를 , 사물을 「 」, 「 」, 「 」ArrayList분류할 수 있도록 하기 위해서는 비교 방법이 필요합니다. 커스텀이 요.compareTo()에서 입니다.ArrayList★★★★★★compareTo() method -1,0,1을 반환합니다.

Java Head 2.0의 해당 챕터를 방금 읽었는데, 아직 배우는 중입니다.

언급URL : https://stackoverflow.com/questions/3718383/why-should-a-java-class-implement-comparable

반응형