inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

김영한의 실전 자바 - 기본편

Arrays.sort

174

ghuhan18

작성한 질문수 121

0

우리는 만약 int[] a = {1,3,2} ; 라고 주어졌다면 Arrays.sort(a) ; 를 하면 되는 것으로 알고 있습니다. 그런데 AudioBook 의 경우에는 사용자가 정의한 객체이기 때문에 sort 의 기준이 명확하지 않아 compareTo 메서드를 사용해야하는 것으로 알고 있어요. 그런데 여기서 AudioBook 객체가 Comparable class 를 반드시 implements 해야하는 이유는 그래야 Arrays.sort() 를 이용할 수 있기 때문인가요? 만약 implements 없이 그냥 사용하면 Arrays.sort() 에서는 compareTo 를 활용해야한다는 인식 자체를 못하는 건가요?

 

아래에는 제가 질문을 하게끔 만든 코드입니다.

 

public class Books
{
    //-----------------------------------------------------------------
    //  Creates a AudioBookCollection object and adds some books to it. Prints
    //  reports on the status of the collection.
    //-----------------------------------------------------------------
    public static void main (String[] args)
    {
        AudioBookCollection library = new AudioBookCollection();
      
        library.addBook("The Kaiju Preservation Society",
          "John Scalzi", "Will Wheaton", 25.99, 482);
        library.addBook("Revenger",
          "Alastair Reynolds", "Clare Corbett", 22.94, 880);
        library.addBook("Klara and the Sun:A Novel",
          "Kazuo Ishiguro", "Sura Siu", 24.50, 616);
        library.addBook("Endurance: Shackleton's Incredible Voyage",
          "Alfred Lansing", "Simon Prebble", 21.83, 620);
        library.addBook("Barbarian Days: A Surfing Life",
          "William Finnegan", "William Finnegan", 21.99, 1088);
     
        System.out.println(library);

        library.sort();

        System.out.println(library);



    }
}
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Arrays;


public class AudioBookCollection
{
    private AudioBook[] collection;
    private int count;
    private double totalCost;

    /*-----------------------------------------------------------------
    * Constructor: Creates an initially empty collection.
    *----------------------------------------------------------------*/
    public AudioBookCollection ()
    {
        collection = new AudioBook[100];
        count = 0;
        totalCost = 0.0;
    }

    /*-----------------------------------------------------------------
    *  Adds an audio book to the collection, increasing the size of the
    *  collection if necessary.
    *----------------------------------------------------------------*/
    public void addBook (String title, String author, String readBy,
                         double cost, int minutes)
    {
        if (count == collection.length)
            this.increaseSize();

        collection[count] = new AudioBook(title, author, readBy, cost, minutes);
        totalCost += cost;
        count++;
    }

    /*-----------------------------------------------------------------
    *  Returns a report describing the Book collection.
    *----------------------------------------------------------------*/
    public String toString()
    {
        Locale usa = new Locale("en", "US");
        NumberFormat fmt= NumberFormat.getCurrencyInstance(usa);

        String report = "~~~~~~~~~~~~~~Wow Cool~~~~~~~~~~~~~~~~~~~~~~~\n";
        report += "My Audio Book Collection\n\n";

        report += "Number of Books: " + count + "\n";
        report += "Total cost: " + fmt.format(totalCost) + "\n";
        report += "Average cost: " + fmt.format(totalCost/count);

        report += "\n\nBook List:\n\n";

        for (int i = 0; i < count; i++)
            report += collection[i] + "\n";

        return report;
    }

        public void sort()
    {	
	    Arrays.sort(collection,0,count);
    } 

    //-----------------------------------------------------------------
    //  Increases the capacity of the collection by creating a
    //  larger array and copying the existing collection into it.
    //-----------------------------------------------------------------
    private void increaseSize ()
    {
        AudioBook[] temp = new AudioBook[collection.length*2];

        for (int i = 0; i < collection.length; i++)
            temp[i] = collection[i];
      
        collection = temp;  
      
    }


}
import java.text.NumberFormat;
import java.util.Locale;

public class AudioBook implements Comparable<AudioBook>
{
    private String title, author, readBy;
    private double cost;
    private int minutes;

    //-----------------------------------------------------------------
    //  Creates a new audio book with the specified information.
    //-----------------------------------------------------------------
    public AudioBook (String title, String author, String readBy, double cost,  int minutes)
    {
        this.title = title;
        this.author = author;
        this.readBy = readBy;
        this.cost = cost;
        this.minutes = minutes;
    }

    //-----------------------------------------------------------------
    //  Returns a string description of this audio book.
    //-----------------------------------------------------------------	

    public String toString()
    {
        // for formatting money
        NumberFormat fmt= NumberFormat.getCurrencyInstance(Locale.US);
        // instead of using the ready-made Locale.US we could also create our own
        // Locale usa = new Locale("en","US")
        // try looking up country locale codes on the web!
      
        // for formatting strings
        String description;
        description = String.format(fmt.format(cost) + "\t" + minutes + "\t"
          + "%-20s" + "\t" + "%-50s",author,title);

        return description;
    }

    // compare based on book length
    public int compareTo(AudioBook other)
    {
        int answer = 0;
	    if (this.minutes<other.minutes){
            answer = -1;
        }
        if (this.minutes>other.minutes){
            answer = 1;
        }
        return answer;
    } 

}

java 객체지향

답변 1

0

y2gcoder

안녕하세요. ghuhan18님, 공식 서포터즈 y2gcoder입니다.

말씀하신 부분처럼, Arrays.sort() 에서 Object[] 타입을 인자로 줬을 때는 해당 array의 모든 요소들이 Comparable 인터페이스를 구현하고 있어야합니다.

image

그리고 Comparable 인터페이스는 compareTo()를 구현하도록 규칙을 정해놨습니다!

image

이에 따라 AudioBook 클래스에서 compareTo를 구현하셨기 때문에(해당 메서드가 인터페이스의 메서드를 구현한 것이라는 점을 확실히 해주기 위해 @Override를 붙여주시면 더 좋을 것 같습니다!)Arrays.sort()의 인자로 사용할 수 있다고 생각해주시면 감사하겠습니다!

 

감사합니다.

질문있습니다

0

28

1

1번 문제 질문입니다.

0

33

1

음악플레이어 문제 중 코드질문

0

27

1

9장 상속 문제와 풀이 질문

0

38

1

강의 자료에 사소한 오타가 있습니다.

0

50

2

매서드 참조값 반환??

0

66

1

접근제어자 - 쇼핑카트 문제에서 상품출력 부분 메서드

0

70

1

자바 기본편 - .(dot)에 관한 질문입니다!

0

85

1

공부방법

0

76

2

상속관계에서 멤버 변수는 오버라이딩 되는 개념이 아닌가요?

0

82

1

static method 질문

0

66

1

캡슐화 문제풀이 ShoppingCart 요구사항에 문제가 있어보입니다. 피드백 주세요

0

97

1

Method1에서 Student 객체

0

74

1

3강 18. null 질문

0

69

1

this 와 super의 호출 순서는 부모-자식관계 떄문만인가요?

0

76

1

팩토리 메서드 패턴과 일반 생성자 사용의 장단점

0

97

1

문의

0

104

1

9장 상속 문제와 풀이 부분 궁금한게 있어서 질문드립니다

0

90

1

상속과 그에 따른 메모리 구조 질문

0

62

1

call메소드에서 멤버에 접근하는 방식을 이해 못 했습니다

0

74

1

수강기한

0

136

1

기본편 객체지향 프로그래밍에 대한 정의

0

87

1

섹션10 상속 메모리 구조 및 문제 관련 질문

0

87

1

추가 지식 학습

0

153

2