2

After creating a

ArrayList<Integer> connectedTo = new ArrayList<>();
connectedTo.add(0,4);
connectedTo.add(3,4);

In the above mentioned statement connectedTo.add(0,4) inserts a value 4 in the zeroth position which is as expected.

But connectedTo.add(3,4) throws a java.lang.IndexOutOfBoundsException. why is this happening?. From my understanding ArrayList are suppose to resize dynamically and allow insertions right?.

Is there any way to overcome this?. Incase of python creating a expression

vertList = {}
vertList[0] = 1
vertList[2] = 3

allows me to save the values in various indexes without any issues. How to implement a code perform's the same operation.

user3280908
  • 162
  • 1
  • 7
  • Are you sure it's NPE and not out of bounds exception? – Maroun Nov 08 '16 at 11:44
  • 2
    the python example you're using is a dictionary, that would equate to a HashMap or HashTable in Java. When you're adding a value to the ArrayList at index 3, it's throws an exception because the ArrayList only has a single element (we might know that it has room for more, but the implementation is hidden). As far as we're concerned, the ArrayList only has a single element. So it is of size 1. – chatton Nov 08 '16 at 11:45
  • The way to do it In python : `list.insert(index, obj)` – Akshay Nov 08 '16 at 12:03

2 Answers2

1

I am afraid you are mismatching two different data types. {} is a dictionary, it allows you to map values. On the other hand, ArrayList is a kind of list which you should initialize in Python by using []. Python code you provided for list won't be working. I suppose, add method you have used adds an element at most at the end of the list.

Take a look at this one: In Python, when to use a Dictionary, List or Set?

This question and its answers will certainly help you understand the difference between most popular collection types and choose the best for your case.

Community
  • 1
  • 1
pt12lol
  • 2,332
  • 1
  • 22
  • 48
1

public void add(int index, E element) Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

Therefore if you want to add an element at a position where position > arraylist.size() it will throw an exception.

What do you want to do with the ArrayList? What do you want to achieve? Maybe you are looking for a Map or you should consider implementing your own data structure.

smsnheck
  • 1,563
  • 3
  • 21
  • 33