繁体   English   中英

用Java中的值对自定义对象数组进行排序

[英]Sorting an array of custom objects by values in Java

我正在处理CS-101,并且只能使用单个阵列。 我有一个看起来像下面的数组:

[Song, Song, Album, Fiction, Movie, Nonfiction, Song]

这是背景的层次结构(我的任务要求):

“在顶层,您将有一个名为Library的类。Library将具有三个子类:Music,Book和Movie。Music将具有两个子类:Song和Album。Book将具有两个子类:Fiction和Nonfction。Movie,Fiction,非功能类,歌曲和专辑将没有任何子类。”

我目前正在尝试编写一种方法,以按图书的ISBN号对图书进行排序。 因此,小说和非小说是我的Book类的子类,而Book类是Library的子类。

我将所有内容都保存在Library myLibrary[] = new Library[100];

我不确定如何只从书籍中检索ISBN并对其进行排序,因为我只允许一个数组。 否则,我希望制作一系列的书籍,然后分别对它们进行排序。

我可以利用哪些提示/算法来完成此任务?

更新资料

如果需要,我可以发布更多代码。 但是这个问题目前更多地集中在方法上。

这里的关键是正确设置继承,而不是实现Comparable接口。 请参见此处的示例: Java Comaprable,然后在父类型的数组上调用.sort(在您的情况下,这将是myLibrary.sort();)这是在原始类型上进行排序的示例: 原始类型数组sort

所以

  1. 在您的子类型上实现可比
  2. 创建父类型的数组并填充它
  3. 在数组上调用sort。

祝好运!

检查是否可行。 (当前在选项卡上,因此无法运行代码)

[我认为排序后,您的书籍将朝着阵列的一侧饱和。 请让我知道结果]

/* book sorting is in decreasing order of ISBN, followed by non book items
The books will be at the beginning of array, other items towards the end */
Arrays.sort(myLibrary, new Comparator<Library>()
    {
        int compare(Library l1, Library l2){
            //if both are books then compare ISBN and return appropriate
            if((l1 instanceof Book) && (l2 instanceof Book)){
                Book b1=(Book)l1; Book b2=(Book)l2;
                if(b1.getISBN()<b2.getISBN) {
                    return -1;
                } else if(b1.getISBN()>b2.getISBN()) {
                    return 1;
                } else {
                    return 0;
                }
            }
            else {//if either one, or none are Book

                //if only l1 is Book, l2 is not
                if(l1 instanceof Book){
                    return 1;
                }

                //if only l2 is Book, l1 is not
                if(l2 instanceof Book){
                    return -1;
                }

                //none are Book
                return 0;
            }
        }
    }
);

干得好...

我先前的回答所述,编写一个新的Comparator并将其用于比较Library对象。

注意:我尚未检查null,但您应该这样做...

class LibraryComparator implements Comparator<Library> {
    public int compare(Library l1, Library l2){
         // If Both are Book instance do the comparison
         if(l1 instanceof Book && l2 instanceof Book){
              // Assuming ISBN is a String or Long field in your class Book
              return ((Book)l1).getISBN().compareTo(((Book)l2).getISBN());
         } else {
         // Otherwise no change in ordering
              return 0;
              // You could specify sorting logic for Movie and Music here as well
         }
    }
}

然后可以对数组进行排序:

Arrays.sort(myLibrary, new LibraryComparator());

在不尝试给出算法的实际实现的情况下,您应该执行就地排序,可以通过以下方式实现优先级:

1.书比音乐和电影优先

2.如果两个对象是“书籍”,则优先级基于ISBN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM