How to sort by alphabetical order (without Comparable or Comparator interfaces)

◇◆丶佛笑我妖孽 提交于 2019-12-20 05:35:17

问题


I came across a problem while practising Java.

I have a class Book which stores the following information:

id (int), author and title

and I have another class BookShelf which store a collection of books using a Vector/ArrayList and have the following methods:

addBook: takes in a book object as input, adds the object into the bookshelf, method returns nothing.

returnListOfBooks: takes in no argument and returns a Vector/ArrayList of all books sorting by title in alphabetical order.

returnListOfBooksByAuthor: takes in author as input and returns a Vector/ArrayList of books by that author

My question is, how do I create the method returnListOfBooks and sort them by title in alphabetical order? It would also be great if you could check my methods and correct me if what i'm doing is wrong.

I have to implement the sorting (bubble sort, insertion sort, and such)

I'm new to java so i'm not quite good at it. Any help would be greatly appreciated!


回答1:


In Java you typically sort a List with Collections.sort and if needed a custom comparator. Java 8 allows a concise syntax for that.

// easy to change for descending order
Collections.sort(listOfBooks, (a, b) -> a.getTitle().compareTo(b.getTitle()));

or even better

Collections.sort(listOfBooks, Comparator.comparing(Book::getTitle));

Mind you that both will sort listOfBooks in place (instead of returning a new sorted list). You probably don't want to do that every time you call returnListOfBooks. If for e.g. inside returnListOfBooksByAuthor you do

Collections.sort(listOfBooks, Comparator.comparing(Book::getAuthor));

The same listOfBooks will be sorted in place according to author this time




回答2:


You would need to make your Book class implement the Comparable interface, and then, compare the names of the books.

Now, the Java Framework already provides a sorting mechanism to sort lists through Collections.sort. If you implement the interface above, you should be able to simply call Collections.sort(listOfBooks) and have your collection sorted.

Alternatively, if you need to implement your own sorting mechanism, you can simply do so and then compare the books by using the .compareTo method which the Comparable interface gives you.




回答3:


While you do need to make your Book objects Comparable to one another, another error you'd likely see with your current code is a concurrent modification exception because you are sorting a list while iterating over it.

So your method should look like this since the requirements are to return a sorted list, not print it.

Note, if you want to keep the initial ordering of listOfBooks before and after calling this method, you'll need to copy the whole list out to another list which you sort and return instead.

public ArrayList<Book> returnListOfBooks()
{
    Collections.sort(listOfBooks);
    // could print them, also, if you wish 
    return listOfBooks; 
}



回答4:


Book Class

import java.util.Comparator;

import java.util.Objects;

public class Book implements Comparable {

private String bookName;
private String autherName;
private String isbn;

public Book(String bookName, String autherName, String isbn) {

    this.bookName = bookName;
    this.autherName = autherName;
    this.isbn = isbn;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

public String getAutherName() {
    return autherName;
}

public void setAutherName(String autherName) {
    this.autherName = autherName;
}

public String getIsbn() {
    return isbn;
}

public void setIsbn(String isbn) {
    this.isbn = isbn;
}

@Override
public int compareTo(Book book) {

    return this.bookName.compareTo(book.bookName);
}

@Override
public int hashCode() {

    int hash = 7;
    hash = 53 * hash + Objects.hashCode(this.bookName);
    return hash;

}
@Override
public String toString(){
    return bookName +" "+autherName + " "+isbn;
}}

Book Shelf

public class BookShelf {

private ArrayList<Book> bookList = new ArrayList<Book>();

public void addBook(Book book) {
    bookList.add(book);
}

public ArrayList<Book> bookList(String sortBy) {

    ArrayList<Book> list = new ArrayList<Book>(bookList);
    SortingComparator comparator = null;
    if (sortBy.equals("auther")) {
        comparator = new AutherComparator();
    } else if (sortBy.equals("bookname")) {
        comparator = new BookNameComparator();
    }
    Collections.sort(list, comparator);
    return list;
}}

Comparators

interface SortingComparator extends Comparator<Book> {}
class AutherComparator implements SortingComparator {
@Override
public int compare(Book b1, Book b2) {
    return (b1.getAutherName().toUpperCase()).compareTo((b2.getAutherName().toUpperCase()));
}

}

class BookNameComparator implements Comparator<Book>,SortingComparator {
@Override
public int compare(Book b1, Book b2) {
    return (b1.getBookName().toUpperCase()).compareTo((b2.getBookName().toUpperCase()));
}}

Main CLass

public static void main(String s[]) {

    BookShelf bookShelf = new BookShelf();

    bookShelf.addBook(new Book("Algorithm", "Toman", "12-34"));
    bookShelf.addBook(new Book("DataBase", "Sethi", "12-35"));
    bookShelf.addBook(new Book("DataStruture", "Ulman", "12-36"));
    bookShelf.addBook(new Book("Network", "Tanenbom", "12-37"));

    ArrayList<Book> list = bookShelf.bookList("auther");
    System.out.println("----Sort by Auther-----------");
    for (Book b : list) {
        System.out.println(b);
    }

    System.out.println("----Sort by Book Name-----------");
    list = bookShelf.bookList("bookname");

    for (Book b : list) {
        System.out.println(b);
    }
}


来源:https://stackoverflow.com/questions/34546443/how-to-sort-by-alphabetical-order-without-comparable-or-comparator-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!