简体   繁体   English

如何通过对象的特定变量的字母顺序将对象添加到数组列表

[英]How to add objects to an Array list by alphabetical order of particular variable of object

I have a library program and within that program is a BorrowBookRecord Record class and a Library class. 我有一个图书馆程序,该程序内有一个BorrowBookRecord Record类和一个Library类。 In the library class contains a 'borrowBook()' method that when called and successfully used, creates a BorrowBookRecord object and adds it to an array list of BorrowBookRecords which is stored in the Library class. 在库类中包含一个'borrowBook()'方法,该方法在调用并成功使用后会创建一个BorrowBookRecord对象,并将其添加到存储在Library类中的BorrowBookRecords数组列表中。 My only problem is I have absolutely no idea how to get the borrowBook() method to store the records in alphabetical order. 我唯一的问题是我完全不知道如何获取借书方式来按字母顺序存储记录。 I wouldn't even know where to start. 我什至不知道从哪里开始。 Each record has a 'student username' as one of its variables which I want to use to as what determines the objects alphabetical order in the list. 每条记录都有一个“学生用户名”作为其变量之一,我想使用它来确定列表中对象的字母顺序。

This is the borrow book method in the library class 这是图书馆课中的借书方法

 public boolean borrowBook(String librarianUsername, String studentUsername, String bookISBN){
    User user = findUserByUsername(studentUsername);

    if(checkPermissionTypeByUserNameBorrow(librarianUsername) && user.isOverBorrow() && checkPermissionTypeByUserNameReserve(studentUsername)){
        if(checkIfAnyAvaliable(bookISBN)){
              for(Book book: books){
                    if(book.getISBNNumber().equals(bookISBN) && book.checkAvaliable()){
                        book.modifyStatus(BookStatus.Reserved);
                        Date date = new Date();

                        BorrowBookRecord record = new BorrowBookRecord(studentUsername, bookISBN, book.getCopyNumber(), date);
                        borrowRecords.add(record);
     /////>>>this is where record is made.
                        user.increaseNumberOfborrowedBooks();
                        break;
                    }
              }                                   
        }
        else{
            throw new IllegalArgumentException("There are no books of that isbn avaliable to borrow");
            }
    }
    else{
        throw new IllegalArgumentException("Student cannot borrow anymore Books/librarian has wrong permissontype");
    }
    return true;
}

In cases where the elements must be stored in a sorted manner based on some criteria, one must go of TreeSet and not ArrayList . 如果必须根据某些条件以排序方式存储元素,则必须使用TreeSet而不是ArrayList

You can replace your data structure to use Java TreeSet so that after every insertion you would have your elements ordered as per given criterion. 您可以替换数据结构以使用Java TreeSet,这样,在每次插入之后,您都可以按照给定的条件对元素进行排序。

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. 元素使用其自然顺序进行排序,或通过在设置创建时提供的Comparator进行排序,具体取决于所使用的构造函数。

Here, you need to provide a Comparator specific to your ordering requirements. 在这里,您需要提供特定于您的订购要求的Comparator So, to order according to studentUsername you must define your Comparator as - 因此,要根据studentUsername进行订购,您必须将Comparator定义为-

public class BookComparator implements Comparator<BorrowBookRecord > {
    @Override
    public int compare(BorrowBookRecord o1, BorrowBookRecord o2) {
        return o1.studentUsername.compareTo(o2.studentUsername);
    }    
}

You can do a binary search with a custom comparator to find the insertion point, as long as you maintain the order: 您可以使用自定义比较器进行二进制搜索以找到插入点,只要您保持顺序:

int index = Collections.binarySearch(borrowRecords, record,
        Comparator.comparing(BorrowBookRecord::getStudentUsername));
if (index < 0) {
    index = -(index + 1);
}
borrowRecords.add(index, record);

Or you can have BorrowBookRecord implement Comparable instead of using a comparator. 或者,您可以让BorrowBookRecord实现Comparable而不是使用比较器。

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

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