这是我的示例代码。这打印出“{test = theClass @ 7096985e}”但我需要它给我类型和范围的值。我尝试了几件事 - 任何方向都会很棒。谢谢!
import java.util.*;
class theClass {
String type;
String scope;
public theClass(String string1, String string2) {
type = string1; scope = string2;
}
}
public class Sandbox {
public static void main(String[] args){
Hashtable<String, theClass> theTable = new Hashtable<String, theClass>();
theClass object = new theClass("int", "global");
theTable.put("test", object);
System.out.println(theTable.toString());
}
}
答案 0 :(得分:5)
只需覆盖班级中的toString
方法。
class theClass{
String type;
String scope;
public theClass(String string1, String string2)
{
type = string1; scope = string2;
}
@Override
public String toString(){
return type+" "+scope;
}
}
答案 1 :(得分:1)
将一个方法toString()添加到你的theClass {},例如
@Override
public String toString() {
return "theClass {type=" + type+", scope= "+scope+"};
}
答案 2 :(得分:1)
您需要覆盖班级中Object
班级提供的toString()方法的默认实施。
@Override
public String toString() {
return "type=" + type+", scope= "+scope;
}
System.out.println()
使用String.valueOf()
方法打印对象,该对象使用对象上的toString()
。如果您没有覆盖类中的toString()
方法,那么它将调用Object
类提供的默认实现,其中包含:
类Object的toString方法返回一个字符串,该字符串由对象为实例的类的名称,符号字符“@”和对象的哈希码的无符号十六进制表示组成。换句话说,此方法返回一个等于值的字符串:
getClass()。getName()+'@'+ Integer.toHexString(hashCode())
因此你得到了这样的输出。
答案 3 :(得分:0)
您的代码正常运行。你确实从哈希表中获取了你的对象。您对对象的字符串表示形式感到困惑。
要显示内部数据,您必须覆盖public String toString()
方法的默认实现。