I’m learning how to use ArrayLists and decided to try making an ArrayList. I have found that I can do:
ArrayList<Object> list = new ArrayList<Object>();
list.add("Hi");
list.add(new Integer(5), 9);
(And I realize that I can just add an int, and it will auto-box it)
The problem is that I cannot put a double or Double inside of the ArrayList at a specified index, which I can do with Integer. I’ve tried like this:
list.add(new Double(4)); // I just redid it, and this one works.
list.add(45.6); // So does this one.
list.add(new Double(4), 6); // it's this one that doesn't.
list.add(43.6, 9); // doesn't work either
So Doubles do fit in an ArrayList, but you can’t specify the index they should be at. If you try, the error that results is:
no suitable method found for add(double, int)
method java.util.ArrayList.add(int,java.lang.Object) is not applicable
(actual argument double cannot be converted to int by method invocation conversion)
method java.util.ArrayList.add(java.lang.Object) is not applicable
(actual and formal argument lists differ in length)
Why won’t it allow a double (or a String) at a specified index, yet it allows an Integer?
Thanks, -AJ
Take a closer look at the error being given. It’s saying you are invoking the
addmethod with two arguments. In this particular case you are passing in adoubleand anint. That method clearly doesn’t exist, even with the generic type erasure.It seems like you really did intend to call the two argument
addmethod. In that case, you have the arguments reversed. The first argument must be the index (position) in the list, while the second argument must be the element being added. Your example should then be:This would be why adding an integer at a specific position worked for you. According to the type-checker, it is technically correct. However, since the first argument was an integer, it interpreted it as the index, whereas you were expecting it to be added to the list.