创建嵌套列表

时间:2012-03-07 18:51:12

标签: java

如何在java中创建嵌套列表?所以我在下面有一个工厂方法,它将列表传递给ROOM类的构造函数。但是我需要将每个墙与一个窗口关联起来,所以当我在构造函数中迭代列表时,它知道某个窗口属于某个墙吗?

public static Room RoomU(){
    List<Room> RoomU = new ArrayList<Room>();

    // THESE TWO SHOULD BE PAIRED AND SO ON...
    RoomU.add(new Walls(Height, Width));
    RoomU.add(new Windows(Height,Width));

    RoomU.add(new Walls(Height, Width));
    RoomU.add(new Windows(Height,Width));

    RoomU.add(new Walls(Height, Width));
    RoomU.add(new Windows(Height,Width));

    RoomU.add(new Walls(Height, Width));
    RoomU.add(new Windows(Height,Width));

    RoomU.add(new Walls(Height, Width));
    RoomU.add(new Windows(Height,Width));

    return new Room(RoomU);
}

4 个答案:

答案 0 :(得分:2)

您正在寻找的可能是Map,而不是列表。

Map<Walls, Windows> myMAp = new HashMap<Walls, Windows>();
mMap.put(new Walls(1,2), new Windows(1,2));

再看一遍,我想也许你应该重构一些更基本的东西,并将windows对象放在wall对象中:

List<Walls> rooms = new ArrayList<Walls>();
rooms.add(new Walls(1,2,new Windows(1,2)));

//--- in Walls class:
Windows windows;

public Walls(int height, int width, Windows windows) {
    this.windows = windows;
    // the rest
}

答案 1 :(得分:0)

对于您描述的用例,最好的方法是使用Map<Walls, Windows>

答案 2 :(得分:0)

您的Room课程需要CollectionWall个对象。

class Room  
{  
   Collection<Wall> walls;  
   ...
}    

class Wall  
{  
    String side;    
    Collection<Window> windows;
    ...
}  

然后,您可以对walls进行迭代,并确定它们所在的side

for(Wall wall : walls)  
{  
    wall.getSide();  
    //do stuff with side
}  

答案 3 :(得分:0)

为什么不让Windows属性为Walls

Windows w = new Windows(height,width);
RoomU.add(new Walls(height, width, w));
                                // ^ seems more object-oriented