Java公共哈希表
因此,我希望能够有一个公共哈希表(有点像您将有一个公共字符串或int等字段)。我该怎么做呢?我试过这样的方法:Java公共哈希表,java,hashtable,Java,Hashtable,因此,我希望能够有一个公共哈希表(有点像您将有一个公共字符串或int等字段)。我该怎么做呢?我试过这样的方法: public class Home { public static Hashtable<String, Double> test = new Hashtable<String, Double>(); public static void main(String[] args) { test.put("A", 1.2);
public class Home {
public static Hashtable<String, Double> test = new Hashtable<String, Double>();
public static void main(String[] args) {
test.put("A", 1.2);
test.put("B", 1.3);
test.put("C", 1.4);
System.out.println(test.get("A");
}
}
公共类主页{
公共静态哈希表测试=新哈希表();
公共静态void main(字符串[]args){
测试。放置(“A”,1.2);
测试。放置(“B”,1.3);
测试。放置(“C”,1.4);
System.out.println(test.get(“A”);
}
}
不过,我希望能够在另一个类中访问哈希表及其信息。执行此操作的方法是什么?我拥有的足够吗?谢谢。您应该能够访问
地图作为主页。测试
public static void main(String[] args) {
Home.test.put("A", 1.2);
Home.test.put("B", 1.3);
Home.test.put("C", 1.4);
System.out.println(Home.test.get("A");
}
但是,您没有添加任何初始值。您需要一个单独的方法来完成此操作。可以使用Home.test
访问映射,如Home.test.put(“a”,1.2)中所述
但您应该使用。请注意,static关键字意味着类的所有实例共享同一个映射,如果您希望每个实例都是唯一的,则必须删除static
关键字
将映射声明为私有(最好使用接口),并提供getter/setter
public class ClassWithTheTable{
private static Map<String, Double> table = new Hashtable<String,Double)>();
public Map<String, Double> getTable(){
return table;
}
public void setTable(Map<String,Double> table){
this.table = table;
}
//Rest of code ommited.
}
带有表格的公共类{
私有静态映射表=新哈希表();
公共映射getTable(){
返回表;
}
公共void可设置(映射表){
this.table=表格;
}
//代码的其余部分被删除。
}
如果多个线程访问变量,您可能希望使用:
public static final Map<String, Double> test = new ConcurrentHashMap<>();
Home.test应该可以工作谢谢,还有其他错误,但这确实有帮助
double value = Home.test.get("A");