简体   繁体   English

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

[英]TreeSet in java not displaying data properly

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: 您必须在Book类中重写toString()方法:

@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 . 首先在Object.toString()找到的默认实现打印不是很有用first.Book@c2ea3f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM