【问题标题】:private TreeMap with objects as values sent to another method to change the objects' properties将对象作为值的私有 TreeMap 发送到另一个方法以更改对象的属性
【发布时间】: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


【解决方案1】:

简答:TreeMap&lt;Integer, obj1&gt; obj1_tmap 的访问修饰符无关紧要。 obj1_tmap 的方法可以被私有和公共访问。

您的方法 1 尝试在 Map.Entry 的值对象中设置属性。另外你的method1必须是类的静态函数,method1不能是类。

因此方法1的代码应该更正为

public class M1 {
    public static void 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.getValue().setProperty1("whatever");
            // set some new properties as well
            the_obj1.getValue().setProperty5("foobar");
         }
    }

}

注意the_obj1.getValue().setProperty1("whatever");。您需要执行 getValue 来获取您最初放入 Map 中的 obj1 myObject。

现在在您的class main 中,您将其称为M1.method1(obj1_tmap);

现在回答您的问题:您正在将 TreeMap 的实例(通过引用传递)传递给 method1,而访问修饰符在这里不起作用。公开不会改变任何事情。

另外请学习基本的java教程。看来您来自 ruby​​/scala/js 背景。此语法在 java 中不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2012-04-03
    • 2012-10-11
    相关资源
    最近更新 更多