T.Su T.Su - 1 year ago 83
Java Question

How do i add data to arraylist by a particular index of array?

Click here for pic of Arraylists in an array Java

Is it possible to add arraylists into array? and I want to insert data into a particular index no of arrray. for example, into arraylist of array[3]. If it isnt possible, how to i solve in another way? I am writing kmeans clustering in java. This is the adding element to particular cluster.

Answer Source

Your question is not very clear, but if what you need is to create an ArrayList of ArrayList's, meaning a parent ArrayList with other ArrayList's as elements you could use generic types, also known as templates.

To declare your parent array you can do something like this, assuming your inner child arrays will contain int values:

ArrayList<ArrayList<Integer>> arrayOfarrays = new ArrayList<>();

In order to access data from one of the inner child arrays you can do something like this:

int value = arrayOfarrays.get(3).get(0);

That line would return the value at index 0 from the child array at index 3. In order to add child arrays you would need to use the add method:

ArrayList<Integer> childArray = new ArrayList<>();
arrayOfarrays.add(childArray); //adds the given array at the last position
arrayOfarrays.add(1, childArray); //adds the given array at index 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download