0

在这个程序中,它应该通过查看其发布年份来按从大到小的顺序对电影列表进行排序。这是方法,我也有打印它的方法。它以 abc 顺序而不是 5、4、3、2、1 顺序对其进行排序。

System.out.println("Sorted by Year - descending:"); 
        sortYears(myMovies,0,myMovies.length-1);
        printMovies(myMovies);

public static void sortYears(Movie4[] myMovies , int low, int high)
    {
        if( low >= high )
            return;

        int mid = (low + high) / 2;

        sortYears(myMovies, low, mid);
        sortYears(myMovies, mid+1, high);
        mergYears(myMovies, low, mid, high);
    }

    public static void mergYears(Movie4[] myMovie, int low, int mid, int high)
    {
        int tempLow = low;
        int tempMid = mid;
        int indexCnt =0;

        while( tempLow < mid || tempMid < high)
        {
            if( tempLow > mid)
            {
                myMovie[indexCnt].equals(myMovie[tempMid]);
                tempMid++;
            }
            else if( tempMid > high)
            {
                myMovie[indexCnt].equals(myMovie[tempLow]);
                tempLow++;
            }
            else if(myMovie[tempLow].getYear() < myMovie[tempMid].getYear())
            {
                myMovie[indexCnt].equals(myMovie[tempLow]);
                tempLow++;
            }
            else
            {
                myMovie[indexCnt].equals(myMovie[tempMid]);
                tempMid++;
            }
            indexCnt++;
        }

        for(int x = low; x < high; x++)
        {
            myMovie[x].equals(myMovie[x-low]);
        }

    } 

电影 4:

public class Movie4 {

    // instance variables 
    String title ;
    int year;
    String studio;

    /**
     * Constructor for objects of class InventoryItem
     */
    public Movie4(String t,int y,String s)
    {
        // initialise instance variables
        title = t;
        year = y;
        studio = s;
    }
    public String getTitle()
    {
        return title;
    }
    public int getYear()
    {
        return year;
    }
    public String getStudio() 
    {
        return studio;
    }
     @Override
    public String toString()
    {
        return title + ", " + year + ", "+studio;
    }
    public boolean equals (Movie4 other)
    {
        return(title.equals(other.getTitle()));
    }
      public int compareTo(Object other) 
        {
        int result;
        String otherTitle = ((Movie4)(other)).getTitle();
        result = title.compareTo(otherTitle);
        return result;
    }
}
4

1 回答 1

0

你如何比较两个Movie4对象?我建议2种方式:

选项1:

您的Movie4类必须equals()重写该方法。这样你的排序逻辑就会正常工作。看到这个

选项#2:

如果你想使用 Arrays.sort() 方法来使用内置排序,你的类必须实现Comparable并且有一个compareTo()方法。看到这个

于 2013-06-01T19:29:44.533 回答