[英]Accessing Map Interface Object created in Main class
Consider the following two classes : 考虑以下两类:
Class A begins here is a separate java file in the same package: 从这里开始, A类是同一包中的一个单独的Java文件:
public class A {
public void putIntoMap(int a[]){
Map <Integer, Integer> intMapObject = new HashMap<Integer,Integer>();
for (int i = 0 ; i < a.length ; i++){
// some code here
}
intMapObject.put(a[i], count);
}
}
Class B begins here is a separate java file in the same package: 从此处开始的B类是同一包中的一个单独的Java文件:
public class B {
public static void main(String args[]){
A a = new A();
a.putIntoMap(arr); // assume arr is an array I already have
// Now I need to do loop over the Map and I need the `intMapObject` //object from above class A
// I need to do something like this
for (Map.Entry<Integer,Integer> e : intMapObject.entrySet()){
// some code here
}
}
How do I access intMapObject
object in class B ? 如何访问B类中的intMapObject
对象?
You can't access variables declared in another method. 您无法访问在其他方法中声明的变量。 Ever. 曾经
But that doesn't mean you can't pass objects from one method to another. 但这并不意味着您不能将对象从一种方法传递到另一种方法。 In this case, I suggest making putIntoMap
return the new map: 在这种情况下,我建议使putIntoMap
返回新地图:
// in A
public Map<Integer, Integer> putIntoMap(int a[]){
Map <Integer, Integer> intMapObject = // ...
// some code to put the stuff in the map here
return intMapObject;
}
// in B
A a = new A();
Map<Integer, Integer> theMap = a.putIntoMap(arr);
for(Map.Entry<Integer, Integer> e : theMap.entrySet()) {
// some code here
}
Note that this does not pass the actual object, but a reference to it. 请注意,这不会传递实际对象,而是传递对它的引用。 In Java, objects are not stored in variables. 在Java中,对象不存储在变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.