java中的TreeSet无法正确显示数据

时间:2012-08-14 07:56:20

标签: java tostring

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]

请有人帮助我。

1 个答案:

答案 0 :(得分:7)

您必须覆盖toString()课程中的Book方法:

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

或尝试更高级的东西:

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

Object.toString()中的默认实现打印效果不大first.Book@c2ea3f