簡體   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