【问题标题】:Using List from one method into another使用 List 从一种方法到另一种方法
【发布时间】:2017-10-30 17:06:06
【问题描述】:
private List<String> add() {
    List<String> strlist = new ArrayList<String>();
    return strList;
}

public void methodOne() {
    List<String> strList = this.add();
}

public void methodtwo() {
    // need to use the list in methodOne.
}

我有一个返回List 的私有方法。我通过在methodOne() 中调用它来执行add() 方法并存储列表值。现在我需要在methodTwo() 方法中使用该列表,而不执行add() 方法或methodOne()。 方法只不过是 RobotFrame Work 中的关键字

是否可以在 Ride 中创建一个 List 变量并存储来自 Method One() 的列表并在 Method Two() 中使用它?

【问题讨论】:

  • 这些都是本地定义的列表,如果你不能使用add,这将不起作用。 methodOne 中的 List 也是本地定义的,因此如果您不返回 List&lt;String&gt; 也不将其存储在与 methodOne 范围不同的任何变量中,则此 List 将很快被垃圾回收你永远无法参考它。
  • 从习惯 Java 的人的角度来看,这是一个奇怪的问题。您能解释一下为什么要在 methodtwo 中使用与在 methodOne 中相同的列表吗?如果您希望多个函数通过对其进行变异来处理同一个对象,则一种解决方案是使用类成员而不是局部变量。但是,您在 add 方法中所做的初始化可能没有意义。

标签: java robotframework


【解决方案1】:

创建类级别列表,以便在方法一执行时填充类级别变量,以便您可以在 methodTwo() 中使用它

【讨论】:

    【解决方案2】:
    public class YourClass{
    
        private List<String> yourList;
    
        private List<String> add(){
            List<String> strlist=new ArrayList<String>();
            return strList;
        }
    
        public void methodOne(){
            yourList=this.add();
        }
    
        public void methodtwo(){
            // here go with yourList variable.
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      修改 methodOne() 使其返回该列表而不是 void

      public List<String> methodOne() {
          List<String> strList = this.add(); 
          .... something else....
          return strList;
      }
      
      public void methodtwo() {
          methodOne(); // here you get a ref to strList...
      }
      

      【讨论】:

        【解决方案4】:
        public void methodOne(){
            List<String> strList=this.add();
        }
        

        使用上面的代码,您不能在 methodOne 的其他任何地方使用 strList,因为它是一个本地列表,其范围不在此方法之外。

        你还有2个选择,

        Option1:
        public List<String> methodOne(){
            List<String> strList=this.add();
            // do SomeOperation on strList because that's why methodOne is there else you can directly call add method from methodTwo()
            return strList;
        }
        
        public void methodtwo(){
          List<String> myLocalList = methodOne(); // Now you have the list :)
        }
        
        
        Option2: Use Instance level list but it's not a good practice
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-10
          相关资源
          最近更新 更多