开发者

Java.ArrayList. method remove()

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());

    }

}

i开发者_开发知识库n 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?


  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.


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) 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.


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. 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜