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