3

Is it possible to create a set indexed objects in ArrayList?

I want to create an array of objects - Portal class - and have them indexed in array which size will be defined by user.

   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();


    }

}

Defining the size of array by user makes using tables not feasible, as we encounter NullPointerException. Is there any other solution to make dynamic size of the table and have the elements indexed?

hubesal
  • 141
  • 3
  • 13

2 Answers2

1
    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 and chrylis are right, a map, or HashMap would probably work best here.

I added an example of how you could implement it. This way you are giving each portal a name and quantity value all in one for loop. The portal name is the key, and the quantity number is the value in my example.

I hope that helps!

Austin B
  • 184
  • 1
  • 1
  • 8
0

You could emulate this behavior with a map that maps from the index to the object:

Map<Integer, Portal> indexes = new HashMap<>();
Mureinik
  • 297,002
  • 52
  • 306
  • 350