• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

List and Autoboxing

 
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have a small program with a Integer List.
After adding a few integers, I just tried to remove using myList.remove(42), and I get IndeOutOfBoundsException while running.

If I use myList.remove(new Integer(42)), it runs without any exception.

Any idea why?

public static void main(String[] args) {

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

al.add(12);
al.add(42);

al.remove(42); //Exception here

Collections.sort(al);
Collections.reverse(al);

System.out.println("size=" + al.size());
for(Integer o: al) {
System.out.println(o);
}
}
 
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are two remove() methods. One takes the list position as a primitive int. The other takes the list element to remove as an object.

al.remove(42) is trying to remove the value at list position 42. The list isn't that long so you get an IndexOutOfBoundsException.

al.remove(new Integer(42)) will remove the array element equivalent to the Integer object.

The remove() method takes an int and you passed an int, so Java doesn't autobox the 42 into an object like you were expecting.
[ July 30, 2006: Message edited by: Scott Johnson ]
 
The only cure for that is hours of television radiation. And this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic