【发布时间】:2016-08-17 11:22:08
【问题描述】:
我的问题基本上是这是否可行,如果不行,为什么不呢?
public class main {
private TreeMap<Integer, obj1> obj1_tmap = new TreeMap<Integer, obj1>();
for(int i = 0;i<100;i++){
//create objects
obj1 myObject = new obj1();
// Set some properties of the object
myObject.setProperty1("BlaBla");
myObject.setProperty2("BlooBloo");
obj1_tmap.put(i,myObject);
}
// Then send this TreeMap to another method
method1(obj1_tmap);
// Iterate over this TreeMap now and hopefully find
//that the underlying objects was changes in method1
}
public class method1(TreeMap<Integer, obj1> the_obj1_treemap) {
// Iterate over this TreeMap to change some of the objects insides properties
for (Entry<Integer, obj1> the_obj1 : the_obj1_treemap.entrySet()){
// Change properties of each object here
the_obj1.setProperty1("whatever");
// set some new properties as well
the_obj1.setProperty5("foobar");
}
}
TreeMap 最初被声明为私有是否重要。公开它会改变任何事情。或者这无论如何都不起作用。你应该从method1发回一个新构建的TreeMap?
提前谢谢你
【问题讨论】:
-
不,没关系,因为您将
TreeMap的实例传递给方法,而不是它的访问修饰符。公开它不会改变任何事情。如果您想发回新地图是无法回答的,因为我们不知道您是要修改旧数据还是要根据传递的地图创建修改后的列表。此外,您不能对方法进行编程,因此这两个类甚至都不是有效的语法。在继续这个之前,我建议先从基本的 java 教程开始,因为这些基本技能无法判断发布的代码(基本上所有内容都是错误的)。 -
另外,您不能在方法内将变量设为私有或公有,这仅适用于类属性。
-
@RayO'Kalahjan 嗯,这是完全错误的,可能表明 java 与
pass-by-reference一起使用 -
@KevinEsche 出了什么问题?
-
@RayO'Kalahjan
everything in Java is passed by reference, except the primitive types,因为基本上所有内容都作为值传递
标签: java pass-by-reference treemap pass-by-value