是否可以在 ArrayList 中创建一组索引对象?
我想创建一个对象数组 - Portal 类 - 并将它们编入数组中,其大小将由用户定义。
import java.util.ArrayList;
import java.util.Scanner;
public class GameFunctions
{
Scanner sc = new Scanner(System.in);
private int portalsQty;
private String[] portalNamesDB = {"name1", "name2", "name3", "name4", "name5"};
ArrayList<Portal> portals = new ArrayList<>();
void setPortalsQty(int portalsQty)
{
this.portalsQty = portalsQty;
}
int getPortalsQty(int portalsQty)
{
return portalsQty;
}
private void createPortals()
{
System.out.println("type the
amount of portals");
portalsQty = sc.nextInt();
System.out.println("number of portals: " + portals.size());
for (int i = 0; i < portalsQty; i++)
{
portals.add(i,p[i]); // CANNOT HAVE VALUES INDEXED LIKE p[i] IN ARRAYLIST
}
}
private void namePortals()
{
int randomNo = (int)(Math.random()*portalsQty);
for (int i = 0; i < portalsQty; i++)
{
System.out.println("Random: " + randomNo);
portals[i].setPortalName(portalNamesDB[randomNo]);
}
}
public void launchGame()
{
createPortals();
namePortals();
}
}
由用户定义数组的大小使得使用表不可行,因为我们遇到了 NullPointerException。是否有任何其他解决方案可以使表格动态大小并索引元素?