I have created a HashSet
which contains elements of type Book(name, author)
. I have implemented the Comparable
interface. But calling Collections.sort()
results an error.
The method
sort(List<T>)
in the typeCollections
is not applicable for the arguments (HashSet<Book>
)
Here is an example where book elements added as below
import java.util.Collections;
import java.util.HashSet;
public class BookHashSetDemo {
public static void main(String[] args) {
HashSet<Book> hashSet=new HashSet<Book>();
Book book1=new Book("ABC","XYZ");
Book book2=new Book("lmn","opq");
Book book3=new Book("rst","uvw");
Book book4=new Book("ABC","XYZ");
hashSet.add(book1);
hashSet.add(book2);
hashSet.add(book3);
hashSet.add(book4);
System.out.println(hashSet);
Book book=new Book();
Collections.sort(hashSet);
}
And this is the class Book
where Comparable
is implemented as below
class Book implements Comparable<Book> {
String name;
String author;
public Book(String name, String author) {
this.name=name;
this.author=author;
}
public String toString() {
return author+"-->"+name;
}
@Override
public int compareTo(Book o) {
// TODO Auto-generated method stub
return name.compareTo(o.name);
}
}
What I am doing wrong? Thanks in advance.