[英]Java - Object Without New Instance
我的程序中有多個類,並且我試圖找到一種在其他類中使用某些方法的方法。 通常我會這樣做:
Class obj = new Class();
但這會為其創建一個新實例,並且由於我使用的是HashMaps,因此無法正常工作,因為它會創建一個新地圖。 我希望它使用已保存的東西使用相同的HashMap。 最好的方法是什么?
編輯:這是我正在談論的代碼的示例:類#1:
public class Foo{
HashMap<String,Integer> hashmap = new HashMap<String,Integer();
hashmap.put("something", 1);
}
第2類:
public class Foo2{
Foo f = new Foo();
f.get("something");
}
f.get沒有任何顯示,因為我創建了它的新版本...有人可以為我更正此代碼,以便我可以看到你們在說什么嗎?
您需要共享對象引用
public class Main {
public static class Foo{
Map<String, Integer> map;
public Foo(Map<String, Integer> map) {
this.map = map; // don't create a new object,
// use one that already exists that can be passed as an argument
}
public void put(String key, Integer value) {
map.put(key, value);
}
public Integer get(String key) {
return map.get(key);
}
}
public static void main(String[] args) {
Map<String, Integer> someMap = new HashMap<>();
someMap.put("aKey", 42);
Foo foo = new Foo(someMap); // the Foo object now references the map you just created
System.out.println(foo.get("aKey")); // prints 42
}
}
在這里,您將創建一個Map
並將其引用的副本作為參數傳遞給您的類的構造函數。 您的班級保存了此引用,並使用它來訪問同一對象。
共享對象時,重要的是要知道您在做什么,以確保更新不會丟失/被覆蓋。
這也是另一種可能的方法。 擴展哈希圖並使類成為單例。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
class ExtHashMap<K,V> extends HashMap<Object,Object> {
private static HashMap<?, ?> map;
public static HashMap<?, ?> getInstance() {
if (map == null) {
map = new HashMap<Object,Object>();
}
return map;
}
private ExtHashMap() {
super();
}
}
public class SampleUtil {
/**
* @param args
*/
public static void main(String args[]) throws Exception {
HashMap map = ExtHashMap.getInstance();
map.put("1", "v1");
HashMap map1 = ExtHashMap.getInstance();
map1.put("2", "v2");
System.out.println(map1.values());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.