-8
ArrayList[] arr = new ArrayList[5];

for(int i=0; i<5; i++)
{
arr[i]= sc.nextInt();
}

Now, to add a given value to a given index I can do:

arr[index].add(value);

but how do I delete a value at a given index?

arr[index].remove(); does not work. It say no method found for remove()

  • Did you mean to create an array of `ArrayList`? Or just one `ArrayList`? – khelwood Jul 16 '17 at 09:38
  • here just one ArrayList – Rishi Kamal Mishra Jul 16 '17 at 09:39
  • You are creating an array of ArrayLists, probably not what you want. Try `ArrayList arr = new ArrayList()` or `int[] arr = new int[5]` – Assen Kolov Jul 16 '17 at 09:40
  • Then you want something like `ArrayList list = new ArrayList<>(5);` – khelwood Jul 16 '17 at 09:40
  • thank you. that helped but then what's the difference between ArrayList arr = new ArrayList(); ArrayList arr = new ArrayList<>(5); and List arr= new ArrayList(); it's confusing after reading manywhere – Rishi Kamal Mishra Jul 16 '17 at 10:06
  • 1
    It's confusing that you can't do any research yourself. [Java - declaring from Interface type instead of Class](//stackoverflow.com/q/3383726) // [Java - declaring from Interface type instead of Class](//stackoverflow.com/q/3383726) – Tom Jul 16 '17 at 10:33

2 Answers2

1

Don't use square brackets with your ArrayList. Lists are not arrays.

ArrayList<Integer> list = new ArrayList<>(5);

Add to it with

list.add(sc.nextInt());

Remove from it with

list.remove(index);
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

As per Oracle documentation

"You cannot create arrays of parameterized types"

If requirement is list which further contain list (refer here), then

    List<ArrayList<String>> hs = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Welcome");
        list.add(" here");
        hs.add(list);
    }

Moreover the working mode of your example will be like:

        ArrayList[] arr = new ArrayList[5];
        for(int i=0; i<5; i++) {
            if (arr[i] == null) {
                arr[i] = new ArrayList<>();
            }
            arr[i].add(21);
        }
Gurpreet Singh
  • 380
  • 4
  • 9