• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

Arrays.sort

24.04.11 10:07 작성 24.04.11 10:35 수정 조회수 86

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;
    } 

}

답변 1

답변을 작성해보세요.

0

y2gcoder님의 프로필

y2gcoder

2024.04.11

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

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

image

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

image

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

 

감사합니다.

채널톡 아이콘