我的程序没有像我想要的那样排序

时间:2013-06-01 19:26:37

标签: java arrays sorting

我是这个程序,它应该通过查看发布年份从最大到最小的顺序对电影列表进行排序。这是方法,我也有一个方法来打印它。它是按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;
    }
}

1 个答案:

答案 0 :(得分:0)

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

选项#1:

您的Movie4课程必须覆盖equals()方法。这样你的排序逻辑就能正常工作。请参阅this

选项#2:

如果要使用Arrays.sort()方法来使用构建内排序,则该类必须实现Comparable并使用compareTo()方法。见this