问题
Attempting to sort arraylist in alphabetical order but the Collection.sort is giving me an error which i do not what to do with it
import java.util.ArrayList;
import java.util.Collection;
/**
*
* @author user
*/
public class BookShelf {
ArrayList<Book> listOfBooks = new ArrayList<Book>();
public void addBook(Book book) {
listOfBooks.add(book);
}
public ArrayList<Book> returnListOfBooks() {
ArrayList<Book> myBook = new ArrayList<Book>(listOfBooks);
Collection.sort(myBook);
return myBook;
}
any help on how to fix this? thanks a lot!
Edit*
Just need to return an arraylist of books which is in order, after changing to Collections, I've gotten another difficulty.
I've change collection import as well
import java.util.ArrayList;
import java.util.Collections;
回答1:
You are using the wrong class. The Class containing the sort(...) method is Collections not Collection
回答2:
You should be using the Class Collections
not Collection
Collections.sort(myBook);
If you don't have duplicates I suggest you to use a TreeSet
.
回答3:
Your using user defined custom class So you need to implement comparable/comparator interface to support sorting
see the below example :
class Book implements Comparable<Book>
{
private String bookName;
public Book(String bookName) {
this.bookName = bookName;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
@Override
public int compareTo(Book o) {
return this.bookName.compareTo(o.bookName);
}
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.bookName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Book other = (Book) obj;
if (!Objects.equals(this.bookName, other.bookName)) {
return false;
}
return true;
}
}
Now You can use sort
//List<Book> list1 = new ArrayList<>();
//Collections.sort(list1);
来源:https://stackoverflow.com/questions/33785901/arraylist-sorting-in-order