0
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();
    }
}

当我运行这个程序时,它显示

[first.Book@c2ea3f, first.Book@a0dcd9, first.Book@1034bb5]

请有人帮助我。

4

1 回答 1

6

您必须覆盖类toString()中的方法Book

@Override
public String toString() {
    return this.title;
}

或尝试更高级的东西:

@Override
public String toString() {
    return "[Book: title='" + this.title + "']";
}

在 prints 中找到的默认实现Object.toString()不是很有用first.Book@c2ea3f

于 2012-08-14T07:57:43.987 回答