首页 > 解决方案 > 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。是否有任何其他解决方案可以使表格动态大小并索引元素?

标签: javaarraylisttable-index

解决方案


    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 循环中为每个门户提供名称和数量值。门户名称是键,数量是我的示例中的值。

我希望这会有所帮助!


推荐阅读