java - ArrayList 中的一组索引对象 - 可能吗?
问题描述
是否可以在 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。是否有任何其他解决方案可以使表格动态大小并索引元素?
解决方案
import java.util.HashMap;
HashMap<Integer, portal>portals = new HashMap<>();
System.out.println("number of portals: " + portals.size());
for (int i = 0; i < portalsQty; i++)
{
int randomNo = (int)(Math.random()*portalsQty);
portals.put(portalNamesDB[randomNo], i);
}
Mureinik 和 chrylis 是对的,地图或 HashMap 可能在这里效果最好。
我添加了一个如何实现它的示例。这样,您就可以在一个 for 循环中为每个门户提供名称和数量值。门户名称是键,数量是我的示例中的值。
我希望这会有所帮助!
推荐阅读
- flutter - Flutter 云消息和通知
- google-apps-script - 如何让一系列文本出现,而不是“范围”这个词
- authentication - 抓取:登录标头已加密:如何发送凭据?
- react-native - Redux 没有更新组件
- swift - Alamofire - 使用未声明的类型“ServerTrustPolicy”?
- javascript - 如何循环 FlatList 嵌套数组
- python - 通过 python selenium 在 chrome 中进行 CPU 节流
- asp.net-mvc - asp.net cshtml 的正确超链接。当前错误的控制器
- c# - 如何在不使用字符串的情况下创建/读取具有特定小数的数字?
- c# - 在 ASP.NET Core 应用程序中使用 WCF 服务几个小时后获取 SecurityNegotationException