Java 创建嵌套列表
如何在java中创建嵌套列表?下面我有一个工厂方法,它将把一个列表传递给ROOM类的构造函数。但是我需要将每面墙与一个窗口相关联,因此当我在构造函数中遍历列表时,它知道某个窗口属于某个墙Java 创建嵌套列表,java,Java,如何在java中创建嵌套列表?下面我有一个工厂方法,它将把一个列表传递给ROOM类的构造函数。但是我需要将每面墙与一个窗口相关联,因此当我在构造函数中遍历列表时,它知道某个窗口属于某个墙 public static Room RoomU(){ List<Room> RoomU = new ArrayList<Room>(); // THESE TWO SHOULD BE PAIRED AND SO ON... RoomU.add(new Wall
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);
}
公共静态室RoomU(){
List RoomU=new ArrayList();
//这两个人应该配对,以此类推。。。
添加(新墙(高度、宽度));
添加(新窗口(高度、宽度));
添加(新墙(高度、宽度));
添加(新窗口(高度、宽度));
添加(新墙(高度、宽度));
添加(新窗口(高度、宽度));
添加(新墙(高度、宽度));
添加(新窗口(高度、宽度));
添加(新墙(高度、宽度));
添加(新窗口(高度、宽度));
归还新房间(RoomU);
}
您要查找的可能是一个列表,而不是列表
Map<Walls, Windows> myMAp = new HashMap<Walls, Windows>();
mMap.put(new Walls(1,2), new Windows(1,2));
Map myMAp=newhashmap();
mMap.put(新墙(1,2)、新窗(1,2));
再看看这个,我认为也许你应该重构一些更基本的东西,让windows对象在walls对象中:
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
}
List rooms=new ArrayList();
添加(新墙(1,2,新窗(1,2));
//---在课堂上:
窗户;
公共墙(内部高度、内部宽度、窗户){
this.windows=windows;
//其余的
}
对于您描述的用例,最好的方法是使用地图
您的房间
类需要收集墙
对象
class Room
{
Collection<Wall> walls;
...
}
class Wall
{
String side;
Collection<Window> windows;
...
}
为什么不将
Windows
设为Walls
的属性
Windows w = new Windows(height,width);
RoomU.add(new Walls(height, width, w));
// ^ seems more object-oriented
Map的方法
put
,add
不存在。
Windows w = new Windows(height,width);
RoomU.add(new Walls(height, width, w));
// ^ seems more object-oriented