繁体   English   中英

如何使用另一个ArrayList的对象创建ArrayList?

[英]How to create an ArrayList with objects of another ArrayList?

所以我有一个ArrayList“ NamedShape”

ArrayList<NamedShape> shapes = new ArrayList<NamedShape>();

包含一个形状和一个字符串,我想要的是拥有另一个ArrayList“ Connection”,它将容纳两个字段,但两者均为“ NamedShape”。 我的ArrayList“连接”将如下所示:

在此处输入图片说明

这是我的“ NamedShape”类:

public class NamedShape {
    private String name;
    private Shape shape;
    public NamedShape( String name, Shape shape ){
        this.name = name;
        this.shape = shape;
    }
    public String getName(){
        return name; 
    }
    public Shape getShape(){ 
        return shape; 
    }
}

这是我的Connection类:

  public class Connection { private NamedShape namedShape1; private NamedShape namedShape2; public Connection(??){ ?? } } 

您能帮我创建这个新的ArrayList“ Connection”吗?

您可以创建另一个包含两个NamedShape对象的类。

public class Connection {
    private NamedShape namedShapeOne;
    private NamedShape namedShapeTwo;
    .............
    .............
    .............
}

现在根据需要创建数组列表

List<Connection> connectionList = new ArrayList<Connection>();

创建一个新的类Connection

public class Connection {

 private NamedShape namedShape;

  //constructors
 //getter setters

}  

然后,您可以创建Connection新数组列表-

List<Connection> connections = new ArrayList<Connection>();

您的问题不言自明。 如果创建ArrayList<Connection> ,则意味着您已经有一个Connection类,在该类中您具有两个NamedShape对象的引用。 因此,如先前的答案所建议,您只需要声明一个Connection类。

如果您不想使用Connection类,那么新的ArrayList将如下所示:

ArrayList<ArrayList<NamedShape>>

即, ArrayList含有ArrayList小号含有NamedShape秒。

谢谢大家,我能够做到。 :d

 ArrayList<Connection> con = new ArrayList<Connection>(); public class Connection { private NamedShape namedShape1; private NamedShape namedShape2; public Connection(NamedShape namedShape1,NamedShape namedShape2){ this.namedShape1 = namedShape1; this.namedShape2 = namedShape2; } public NamedShape getNamedShape1(){ return namedShape1; } public NamedShape getNamedShape2(){ return namedShape2; } public void setNameShape1(){ this.namedShape1 = namedShape1; } public void setNameShape2(){ this.namedShape2 = namedShape2; } } 

暂无
暂无

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

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