1
votes

ArrayList have metod remove(int index) and remove(Object o), so

i try run this code: public static void main(String args[]){

    ArrayList<Long>ar=new ArrayList<Long>();

    ar.add(11L);
    ar.add(22L);
    ar.add(33L);

    ar.remove(new Integer(33)); // 1

    byte b =0;
    ar.remove(b);  //2

    for(Iterator i=ar.iterator(); i.hasNext();)
    {
        System.out.println(i.next());

    }

}

in result i have:

22
33

My question:

  1. in line 1 parameter Integer - why we not have exception?

  2. line 2 - paramenet byte - its not int and not Object, why not Exception again?

6
so, if i correctly understand for line 1 we have this situation: in our list we have Long, so when we try run remove method we have this: If(Integer.equals(Long)) returns false, our list not modified.user471011
and next. byte -> int. its correct. but if i do this: long b =4654654654654654654L; long to int - imposible.user471011

6 Answers

5
votes
  1. The remove(..) method is not generic. It accepts any object and does not check its class. The condition it should meed in order for an element to be remove is the equals(..) method to return true when compared to an element in the collection. The element 33 is not removed, because Long.equals(..) returns false if the other object is not instanceof Long

  2. the byte is interpreted as the index.

2
votes

Because both of those get cast to the correct type. In the first one, it is remove(Object o) where o is Integer(33). But it dooesn't find that object in your arraylist, so it returns false as per the definiton:

Returns: true if this list contained the specified element.

The second probably gets cast to an int so you're removing the first index.

1
votes

1) You pass an object that is not in the list. So nothing happens.

2) It is not a object that is passed, but an index (0). So the first element in the arraylist is removed.

1
votes

Java has built in autoboxing to save you the time of typecasting various numeric representations. No error because Java figures out what you meant and converts it for you.

1
votes
  1. The Integer is being converted to an Object and thus does not throw an exception.
  2. I reckon the byte is being converted to an int and is being treated as index 0 thus removing the first value.
0
votes

Take a peek at the javadocs. ArrayList.remove takes an Object and an Integer is is an Object.

[update] forgot to answer the second question.

The byte works because I believe it is either autoboxed into an Object or else it is upcast to an int as an index.