JAVA compareTo

한주영·2023년 8월 24일
0

java

목록 보기
1/1

compareTo 함수는 Comparable 인터페이스에서 제공하는 함수이며,
두개의 값을 비교해 int값으로 반환해주는 함수이다

int compareTo(T other)

T는 비교하려는 객체
정수값을 반환

EX) Person클래스를 통해 compareTo사용법

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 this.age - other.age;
    }
    @Override
    public String toString() {
        return name + " (" + age + " years old)";
    }
}
public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("Alice", 30);
        Person person2 = new Person("Bob", 25);
int result = person1.compareTo(person2);
if (result < 0) {
            System.out.println(person1 + " is younger than " + person2);
        } else if (result > 0) {
            System.out.println(person1 + " is older than " + person2);
        } else {
            System.out.println(person1 + " and " + person2 + " are the same age");
        }
    }
}

해당 예제는 Person클래스에서 나이와 이름을 필드로받아서
메인에서 Person객체를 생성한후
이름,나이를 입력받은후에 비교하는 예제이다

profile
백엔드개발자가 되고싶은 코린이:)

0개의 댓글

Powered by GraphCDN, the GraphQL CDN