Kiwi Bird
Kiwi Bird

Reputation: 145

Questions about ArrayList

I need to use an ArrayList, but I am not sure how to do some of these things that would be possible with a normal array.

1) This:

int[][] example1 = new int[10][20];

(An array with two arguments (10, 20)) is possible with normal arrays, but how to do it with an ArrayList.)

2) How to increase the value of an int on the list by 1, like this:

example2[3][4] ++;

Upvotes: 0

Views: 128

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

To mimic a multidimensional array using collections you would use:

List<List<Integer>> list = new ArrayList<>(); //Java 7

List<List<Integer>> list = new ArrayList<List<Integer>>(); //Pre Java 7

So lets say we create a List<List<Integer>> where the outer List contains 10 List<Integer> and the inner list contains 10 Integers. To set the fifth element on the fourth list:

public static void main(String[] args) {
    List<List<Integer>> outer = new ArrayList<List<Integer>>();
    for(int x = 0; x < 10; x++){
        List<Integer> inner = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        outer.add(inner);
    }
    //Remember that Integer is immutable
    outer.get(3).set(4, new Integer(outer.get(3).get(4)) + 1);
}

Upvotes: 1

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

ArrayList is dynamically growable list backed by array.

List<List<Integer>> list = new ArrayList<List<>>(10);

you can get an element of list by List#get.

List<Integer> innerList = list.get(3);
Integer integer = innerList.get(4);

Update value by List#set -

list.get(3).set(4,list.get(3).get(4)++);

NOTE : Integer class is immutable.

Upvotes: 7

RaptorDotCpp
RaptorDotCpp

Reputation: 1465

The equivalent of your declaration with an ArrayList is:

List<List<Integer>> example1 = new ArrayList<>();

You have to use Integer because Java Collections do not support primitive types. Check out this page of the Oracle docs for more information on Autoboxing and Unboxing.

Since an ArrayListcan grow dynamically, you don't need to give a size. If you want it to have an initial size, you can pass that as an argument to the constructor.

You can get elements from an ArrayList (or any Class implementing the List interface) by using the get() method with the index of the element as an argument.

Using example.get() on example1 will give you an object of the type List. You can then use get() again to get an Integer.

Upvotes: 0

Vimal Bera
Vimal Bera

Reputation: 10497

  1. int[][] example1 = new int[10][20];
    you can do it in arraylist by using this syntax :

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

  1. example2[3][4] ++;
    This can be same in arraylist as by using this :

int val = (a.get(0).get(0)) + 1;

Upvotes: 0

Related Questions