2016-09-24 3 views
3

먼저 API 디자인에 의해 제한된다는 점을 알려주십시오. API를 변경하지 마십시오. 그러나 개인 기능을 추가 할 수 있습니다.다른 함수에서 'Comparator'를 반환하십시오.

public class Point implements Comparable<Point> { 

    public Point(int x, int y)    // constructs the point (x, y) 
    public void draw()      // draws this point 
    public void drawTo(Point that)   // draws the line segment from this point to that point 
    public String toString()    // string representation 

    public int compareTo(Point that)  // compare two points by y-coordinates, breaking ties by x-coordinates 
    public double slopeTo(Point that)  // the slope between this point and that point 
    public Comparator<Point> slopeOrder() // compare two points by slopes they make with this point 
} 

slopeOrder() 메서드의 비교 함수를 재정의하려고하면 문제가 발생합니다. 나는 메서드를 slopeOrder() 함수에서 호출하려고 시도했지만, API에 매개 변수가 없으므로 사용할 수 없습니다.

slopeOrder() 방법에서 Comparator<Point>을 반환하는 몇 가지 해결책을 제안하십시오.

+0

는 ASM처럼 보입니다.) 해당 회선 주석이 포함되어 있습니다.) – Antoniossss

+0

비교를 요청해야합니까? 포인트가 비슷하면 비교기가 필요한 이유는 무엇입니까? 반환해야하는 비교기가 다른 순서를 정의해야하는 것처럼 보입니다. –

+0

그것은 coursera (algs4)의 과제 중 하나인데, 논리 부분을 못 박았지만 Comparator 인터페이스를 다루는 것은 이번이 처음입니다. – Shanky

답변

1

당신은 람다 표현식을 사용하여 Comparator<...>를 인스턴스화 할 수 있습니다 :

다음
public Comparator<Point> slopeOrder() { 
    return (a, b) -> { 
     // code here 
    }; 
} 

, ab 비교되는 점이다. 당신은 자바 8 이하라면

은 또는, 당신은 익명 클래스를 사용해야 할 것 다음 Comparator이 statless 인 경우

public Comparator<Point> slopeOrder() { 
    return new Comparator<Point>() { 
     @Override 
     public int compare(Point a, Point b) { 
      // code here 
     } 
    }; 
} 

, 당신은 1 개 인스턴스를 생성하고 static final 필드로 저장할 수 있습니다, 그리고 그냥 항상 그 인스턴스를 반환합니다.

물론 Comparator<Point>을 구현하는 새 클래스를 만들고 대신 해당 클래스를 인스턴스화 할 수도 있습니다.

+0

그 덕분에 괜찮 았어! 나는 람다 식을 조사 할 것이다. – Shanky

+1

비교기는 항상 * 상태 비 저장 *입니다. 이 특정 비교자는 문맥 적입니다. 즉, 비교 대상 슬로프를 계산하기 위해 현재 '점'을 사용하기 때문에 싱글 톤이 될 수 없습니다. – Andreas

0

두 점을 this 점으로 비교할 수 있습니다. slopeOrder() 방법의 설명 이후

public Comparator<Point> slopeOrder() { 
    final Point that = this; 
    return new Comparator<Point>() { 

     public int compare(Point o1, Point o2) { 
      return Double.compare (o1.slopeTo(that) - o2.slopeTo(that)); 
     } 
    }; 
} 
+0

'double '값을 비교하기 위해'd1 - d2'를 사용하지 마십시오. 'Double.compare (d1, d2)'를 사용하십시오. – Andreas

3

은 다음과 같습니다

슬로프 그들은 ​​당신이 값을 비교해야 의미이

에게 로 만들로 두 점을 비교 각 개체에 slopeTo(Point that)을 호출하여 반환되었습니다. 해당 메서드의 반환 값이 double 인 경우 Double.compare()에 전화해야한다는 의미입니다. 모두

public Comparator<Point> slopeOrder() { 
    return (o1, o2) -> Double.compare(slopeTo(o1), slopeTo(o2)); 
} 

: 자바 8에서

public Comparator<Point> slopeOrder() { 
    return new Comparator<Point>() { 
     @Override 
     public int compare(Point o1, Point o2) { 
      return Double.compare(slopeTo(o1), slopeTo(o2)); 
     } 
    }; 
} 

, 즉 람다 표현식으로 작성하기가 훨씬 더 간단 :

사전 자바 8에서는 익명 클래스를 사용하여 구현하는 것 예를 들어, slopeTo() 호출은 slopeOrder() 호출의 this 개체에서 호출됩니다.

관련 문제