[정보] 잡동사니

[JAVA] Java compareTo() 메서드 사용법

  • -
반응형

Java compareTo() 메서드 사용법

Java에서 compareTo() 메서드는 두 개의 객체를 비교하는 데 사용됩니다. 이 메서드는 주로 String, Integer, Double 등의 비교 가능한(Comparable 인터페이스를 구현한) 클래스에서 사용됩니다.

 

 

 

 

 

 

1. compareTo() 메서드의 기본 문법


public int compareTo(T obj)

📌 반환 값

반환 값 의미
0 두 객체가 같음
음수 (< 0) 현재 객체가 비교 대상보다 작음
양수 (> 0) 현재 객체가 비교 대상보다 큼

 

 

 

 

 

 

 

 

2. compareTo() 예제

(1) String 비교

문자열을 사전순(알파벳 순서)으로 비교합니다.


public class CompareToExample {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";
        String str3 = "apple";

        System.out.println(str1.compareTo(str2));  // 음수 (-1)
        System.out.println(str1.compareTo(str3));  // 0 (같음)
        System.out.println(str2.compareTo(str1));  // 양수 (1)
    }
}

 

 

 

 

 

 

 

 

출력 결과


-1
0
1

📌 "apple".compareTo("banana")"apple""banana" 보다 앞에 오므로 음수를 반환합니다.

 

 

 

 

 

 

 

 

 

(2) Integer 비교


public class IntegerCompare {
    public static void main(String[] args) {
        Integer num1 = 10;
        Integer num2 = 20;
        Integer num3 = 10;

        System.out.println(num1.compareTo(num2));  // -1
        System.out.println(num1.compareTo(num3));  // 0
        System.out.println(num2.compareTo(num1));  // 1
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

(3) 사용자 정의 클래스에서 compareTo() 사용

Comparable 인터페이스를 구현하면 사용자 정의 객체도 비교할 수 있습니다.


class Person implements Comparable<Person> {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age);
    }
}

public class ComparePerson {
    public static void main(String[] args) {
        Person p1 = new Person("Alice", 25);
        Person p2 = new Person("Bob", 30);

        System.out.println(p1.compareTo(p2));  // -1 (Alice는 Bob보다 나이가 적음)
    }
}

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.