2013-07-08 20 views
0

这是我的示例代码。这会打印出“{test = theClass @ 7096985e}”,但我需要它给我类型和范围的值。我尝试了几件事 - 任何方向都很棒。谢谢!在以对象为值的Java哈希表中,如何返回对象值?

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

覆盖'toString()' – johnchen902

+1

一些关于代码的评论与你的问题无关。 1.按照定义,类名以大写字母开头。 (TheClass而不是theClass)这使得其他人更易读。 2.使用HashMap而不是Hashtable。虽然Hashtbale可以正常工作,但它是一个比HashMap慢的实现。 3.不要给你的参数命名字符串1,字符串2等。给它们命名为“范围”和“类型”。这使得更容易理解您的方法被其他人调用时的目的。 – ssindelar

回答

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

用于'@ Override'的+1。 – Maroun

+0

像冠军一样工作!非常感谢!我一直在为此工作数小时。 – bstrong

1

将toString()方法添加到theClass {}例如,

@Override 
public String toString() { 
    return "theClass {type=" + type+", scope= "+scope+"}; 
} 
+0

Thx,为我输入代码彼得......你太快了。 – Frank

0

您的代码正常工作。你的确从哈希表中获得你的对象。你对你的对象的字符串表示感到困惑。

要显示内部数据,您必须覆盖public String toString()方法的默认实现。

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()方法)

因此你这样的输出。