본문으로 바로가기

[JAVA][Comparable ]

category 카테고리 없음 2018. 3. 23. 09:03

         

Comparable 인터페이스 예제

 

1

2

3

4

5

6

7

8

public class Person {

    public String name;

    public int age;

    

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

Colored by Color Scripter

cs

 

 

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package day4;

 

public class Person implements Comparable<Person> {

    // Comparable 인터페이스를 상속받는다

    public String name;

    public int age;

    

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    @Override

    public int compareTo(Person o) {

        // 상속받은 인터페이스에 있는 compareTo()메서드를 구현

        // TODO Auto-generated method stub

        if(age < o.age) return 1;

        // 현재 age compareTo()메서드의 매개변수값으로 받은

        // Person클래스 타입의 o객체의 age 비교한다.

        // o.age  클때, 1 반환하면 내림차순 / -1 반환하면 오름차순으로 정렬한다.

        else if(age == o.age) return 0;

        else return -1;

    }

}

Colored by Color Scripter

cs

 

 

 

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package day4;

 

import java.util.Iterator;

import java.util.TreeSet;

 

public class ComparableExample {

    public static void main(String[] args) {

        TreeSet<Person> treeSet = new TreeSet<Person>();

        

        treeSet.add(new Person("박정윤"15));

        treeSet.add(new Person("조성규"50));

        treeSet.add(new Person("김선영"35));

        

        Iterator<Person> iterator = treeSet.iterator();

        while(iterator.hasNext()) {

            Person person = iterator.next();

            System.out.println(person.name+":"+person.age);

        }

    }

 

}

Colored by Color Scripter

cs

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package day4;

 

import java.util.Iterator;

import java.util.TreeSet;

 

public class ComparableExample {

    public static void main(String[] args) {

        TreeSet<Person> treeSet = new TreeSet<Person>();

        

        treeSet.add(new Person("박정윤"15));

        treeSet.add(new Person("조성규"50));

        treeSet.add(new Person("김선영"35));

        

        Iterator<Person> iterator = treeSet.iterator();

        while(iterator.hasNext()) {

            Person person = iterator.next();

            System.out.println(person.name+":"+person.age);

        }

    }

 

}

Colored by Color Scripter

cs

 

비교해서 출력.