public class Book {
String title;
public Book(String t) {
title = t;
}
}
public class Bookcomparator implements Comparator<Book> {
public int compare(Book one, Book two) {
return (one.title.compareTo(two.title));
}
}
public class TreesetTest {
public void go() {
Book b1 = new Book("How");
Book b2 = new Book("Remix");
Book b3 = new Book("Finding ");
Bookcomparator bc = new Bookcomparator();
TreeSet<Book> set = new TreeSet<Book>(bc);
set.add(b1);
set.add(b2);
set.add(b3);
System.out.println(set);
}
}
public class Test {
public static void main(String args[]) {
TreesetTest t = new TreesetTest();
t.go();
}
}
when I run this prog it displays
[first.Book@c2ea3f, first.Book@a0dcd9, first.Book@1034bb5]
Please somebody help me.
You must override toString()
method in your Book
class:
@Override
public String toString() {
return this.title;
}
or experiment with something fancier:
@Override
public String toString() {
return "[Book: title='" + this.title + "']";
}
The default implementation found in Object.toString()
prints not very useful first.Book@c2ea3f
.
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.