gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:33:29 26 4
gpt4 key购买 nike

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]

请有人帮助我。

最佳答案

您必须重写 Book 类中的 toString() 方法:

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

或者尝试一些更奇特的东西:

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

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

关于java - java中的TreeSet无法正确显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11948034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com