2017-12-20 28 views
-3

이것은 아주 간단한 문제이지만 자바가 무엇을 원하는지 알아낼 수 없었습니다. 지금 나는 단순히 코드를 가지고 입증 :비교기를 초기화하는 방법은 무엇입니까? 그것은 변수가 초기화되지 않았다고 말합니다.

Comparator<Integer> c;  

if (c.compare(5, 3) < 0) { 
    System.out.println("yep, it's less"); 
} 

도 물론 비교를 import java.util.Comparator;

넷빈즈를 가져 오는 동안이 나에게 말한다 "변수 c를 초기화되지 않았을 수 있습니다." c을 초기화하려면 어떻게해야합니까? 그러나 비교기를 사용

건배

이 당신이 원하는 무엇
+0

https://www.mkyong.com/java/java-object-sorting-example-comparable을 X를 좌표 것 인 것이다 -and-comparator/ –

+1

의미있는 방식으로 비교기를 정의해야합니다. –

+0

다음 줄에서만 비교기를 사용할 필요는 없습니다. 'if (5 <3)'라고 써도 될 것입니다. 아이디어는 논리를 정의하는 코드와이를 사용해야하는 코드를 분리하는 것입니다. 그래서 당신은 그것을 방법으로 전달하려고 할 것입니다. – Thilo

답변

-1

(자바 8)

import java.util.Comparator; 

public class ComparatorDemo { 
    public static void main(String... args) { 

     // (1) Defining a custom comparator using lambda 
     // Comparator<Integer> c = (Integer a, Integer b) -> a - b; 

     // (2) comparingInt takes a lambda which maps from object you want to compare to an int 
     Comparator<Integer> c = Comparator.comparingInt(a -> a); 

     if (c.compare(3, 5) < 0) 
      System.out.println("Yes, It's less"); 
    } 
} 

, 약간 더 복잡한 클래스의 경우에 더 의미가있다. 예를 들어, 다음은 당신이 당신이 그들의 사용하여 두 점을 비교하는 비교기를 원한다면 할

import java.util.Comparator; 

class Point { 
    private int x; 
    private int y; 

    public Point(int x, int y) { this.x = x; this.y = y; } 
    public int getY() { return y; } 
    public void setY(int y) { this.y = y; } 
    public int getX() { return x; } 
    public void setX(int x) { this.x = x; } 
} 

public class ComparatorDemo { 
    public static void main(String... args) { 
     Comparator<Point> pc = Comparator.comparing(Point::getX); 
     Point p1 = new Point(1, 2); 
     Point p2 = new Point(2, 2); 
     if (pc.compare(p1, p2) < 0) { 
      System.out.println("Yes, it's less"); 
     } 
    } 
}