-7

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 type Collections 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.

Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
shruti kharge
  • 115
  • 1
  • 2
  • 8

1 Answers1

2

Collections.sort() accepts a List, but you are trying to pass a Set to it, thus an error occurs.

According to the example given in the question, it's better to use a TreeSet:

Set<Book> books = new TreeSet<>();

And, if the Book class implements Comparable<Book> interface, then you can just write:

books.add(new Book("DEF", "XYZ"));
books.add(new Book("ABC", "XYZ");

TreeSet elements will be ordered according to the Book.compareTo(...) method implementation.

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90