0
    import java.util.TreeSet;
    
    public class TestTree {
        
        public static void main(String[] args) {
            
            new TestTree().go();
        }
        
        public void go() {
            
            Book b1 =  new Book("How cats Work");
            Book b2 =  new Book("Remiz your body");
            Book b3 =  new Book("Finding Emo");
            
            
            TreeSet<Book> tree = new TreeSet<Book>();
            tree.add(b1);
            tree.add(b2);
            tree.add(b3);
            
            System.out.println(tree);
                        
        }
    
    }
    
    class Book implements Comparable{
        
        String title;
        
        public Book(String t) {
            
            title = t;
        }
    
        @Override
        public int compareTo(Object o) {        
            Book book = (Book) o;
            return (title.compareTo(book.title));
        }
    }

Query

Getting output as : [programs.Book@5a10411, programs.Book@2ef1e4fa, programs.Book@306a30c7]

But need output : Finding Emo , How cats Work , Remiz your body

Expected output should be title of the books been sorted. But while printing tree object getting the >>object values :( Could some one help to sort out what mistake i have done? I am new to collections and learning them, need some help friends.

Siva
  • 17
  • 7
  • 1
    The `TreeSet#toString()` method iterates over its elements and invokes `toString()` on them (with a `, ` between elements, a `[` prefix, and a `]` suffix). You need to override `Book#toString()` if you want to return the title instead of the default value. – Slaw Sep 22 '20 at 04:53
  • Thank you @Slaw it worked after overriding toString() method. – Siva Sep 22 '20 at 04:56

0 Answers0