简体   繁体   中英

How to sort the elements of an ArrayList<> alphabetically?

I have created an ArrayList of FictionBooks and I'm trying to sort them alphabetically by the Author's name. Here's the code that I have so far.

import java.util.*;
import java.util.Collections;

public class Library implements Comparator<FictionBook> {
    private static final int CAPACITY = 200;
    public ArrayList<FictionBook> fictionBooks;

    public Library() {
        fictionBooks = new ArrayList<FictionBook>();
    }

    //...

    @Override
    public int compare(FictionBook o1, FictionBook o2) {
        if(o1.getAuthor() != null && o2.getAuthor() != null){
            return o1.getAuthor().compareTo(o2.getAuthor());
        }
        return 0;
    }

    public void sort() {
        Collections.sort(fictionBooks, String.CASE_INSENSITIVE_ORDER);
    }
}

But whenever I try to use Collections.sort it gives me this error for sort:

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (ArrayList<FictionBook>, Comparator<String>) I will be grateful if you come up with a solution to my problem and share it with others.

The FictionBooks Comparator is Library . This

 Collections.sort(fictionBooks, String.CASE_INSENSITIVE_ORDER);

should be something like

 Collections.sort(fictionBooks, this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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