所以我有这个方法,我需要返回一个数组列表的所有对象。但无法弄清楚如何(我什至不知道我是否应该使用数组列表)。
问题是我将有未知数量的对象需要在一个返回语句中传递。所以我目前将它们存储在名为表的数组列表中。
这是我的代码:
public GuestTable[] GetSeatingChart(String filename) {
GuestTable table1 = new GuestTable();
GuestTable table2 = new GuestTable();
GuestTable table3 = new GuestTable();
table1.AddGuestToTable(47);
table2.AddGuestToTable(53);
table3.AddGuestToTable(53);
tables.add(table1);
tables.add(table2);
tables.add(table3);
return new GuestTable[] {tables.get()};
}
我的问题在
return new GuesTable[] {tables.get()};
数组列表没有 getAll()
函数,所以我有点卡住了。由于数组列表中的元素数量也就是表的数量每次都会不同,我不能只在 return 语句中使用一些静态的东西。
这个项目是期末项目,我是编程新手。
-谢谢迈克
最佳答案
ArrayList
有一个方法:
toArray(T[] arr);
因此您可以轻松地使用它:
GuestTable[] tablesArray = new GuestTable[tables.size()];
tables.toArray(tablesArray);
return tablesArray;
或者您可以简单地更改方法签名以返回 ArrayLists
:
public ArrayList<GuestTable> GetSeatingChart(String filename) {
关于java - 从数组列表中返回一个常规数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132076/