gpt4 book ai didi

java - ArrayList 中的一组索引对象 - 这可能吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:18 27 4
gpt4 key购买 nike

是否可以在 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 是对的, map 或 HashMap 可能在这里最有效。

我添加了一个示例来说明如何实现它。通过这种方式,您可以在一个 for 循环中为每个门户指定一个名称和数量值。在我的示例中,门户名称是键,数量是值。

希望对您有所帮助!

关于java - ArrayList 中的一组索引对象 - 这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50746697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com