+ Start a Discussion
Ken_KoellnerKen_Koellner 

list.add(0,element) faults on empty list.

I guess this is more a rant than a question.

 

Do this--

 

List<Integer> myList = new list<Integer>();
...
myList.add(0,86);

 

And your program faults with an index out of bounds exception.

 

That forces you to code --

 

List<Integer> myList = new list<Integer>();
...
if (myList.size() == 0) { myList.add(86); } else { myList.add(0,86); }

 

It would be nice if you add(0,newElement) just added the element to the beginning of the list regardless of whether it had any members yet.

 

Java documentation on list.add() says -- IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

 

So in Java index == size() would be legal. 

 

Why didn't they just to that in Apex?

 

 



goabhigogoabhigo

Which line is causing this error?

Ken_KoellnerKen_Koellner

If you do myList.add(0,xyzzy); on an empty list, you get an index out of bounds exception.