简体   繁体   English

将ArrayList对象分配给实例变量-Java

[英]Assigning ArrayList object to Instance variable - java

The code snippet below is part of some code I am reading for an assignment but I cant understand the role of the copy variable in the snippet or what it does. 下面的代码段是我正在阅读的一些代码的一部分,但我无法理解该代码段中copy变量的作用或其作用。 I know its an instance of the Sample class, but why it is then assigned an ArrayList is not clear to me. 我知道它是Sample类的一个实例,但是为什么我不知道为什么要为其分配一个ArrayList

public class Sample implements Var{

   private List lst1;
   private List lst2;

   public Sample() {        
        super();
     }

    public Sample(List lst1) {      
         this();
         this.lst1 = lst1;
     }

    public List getLst1() {
        return lst1;
    }

    public void setLst1(List lst1) {
       this.lst1 = lst1;
    }

    @Override
    public Var copy(){
         Sample copy = new Sample(lst1);    
         copy.lst2 = new ArrayList(lst2);
         return copy;
    }

    @Override
    public void randomize(){

    }
}

In fact the error message is explicit to show that you can't iterate over the variable copy because you haven't implemented the Iterable interface which allows you to do it. 实际上,错误消息是明确的,表明您无法遍历变量copy因为尚未实现允许您执行的Iterable接口。 If you insist to loop over it and to have functions allowing you to do so: just visit this link Java Generics - Implementing the Iterable Interface where you can for exemple (if this is what you want) iterate over the elements of the two lists of an instance lst1 and lst2 如果您坚持要遍历它,并具有允许您这样做的功能:只需访问此链接Java泛型-实现Iterable接口 ,您可以在其中举例说明(如果您要的话)对以下两个列表的元素进行迭代实例lst1lst2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM