`
frank-liu
  • 浏览: 1666763 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ArrayList.remove()的一个小细节

    博客分类:
  • java
 
阅读更多

不废话,先上代码:

 

ArrayList<Integer> col = new ArrayList<Integer>();
System.out.println("Initial size: " + col.size());
for(int i = 0; i < 20; i++)
    col.add(i + 10);

 

显然,上面这段代码再简单不过了,建立一个Interger类型参数的ArrayList.

于是考虑到要从ArrayList删除两个元素,比如10, 25。初步设想的代码如下:

 

col.remove(10);
col.remove(25);

 

   基于这种设想的原因是,既然ArrayList<Integer>里的类型是Integer,我传入一个int的应该可以自动实现autoboxing.那么,如果和设想的一样,col中的10和25两个元素都被删除了。

实际运行的结果不然:

 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 25, Size: 20

at java.util.ArrayList.rangeCheck(ArrayList.java:604)

at java.util.ArrayList.remove(ArrayList.java:445)

at CollectionBasics.main(CollectionBasics.java:54)

从错误中间可以看到,提示的是访问数组索引越界了。怎么会这样呢?很显然,传入的10,25被当成索引而不是要移除的元素。
察看java doc里面才发现,里面有两个remove方法,分别定义如下:
public E remove(int index);

public boolean remove(Object o);
 
当我们传入int类型的时候,会自动被当成上面那个方法来调用。而下面那个移除某个特定元素的方法是需要传入一个Object对象。所以,为了移除制定的元素而不至于引起混淆的话,可以将传入的int先封装一下:
col.remove((Integer)10);
col.remove((Integer)25);
    这样结果就对了。

 

10
1
分享到:
评论
5 楼 793059909 2014-07-08  
frank-liu 写道
793059909 写道
重载有优先级?
837062099 写道
重载方法中,调用优先级最高的是最精确的方法。

这样的重载,确实很容易是调用者发生错误,以前我自己写的这样的方法,找了好久才发现这个错误。


因为在这里remove方法接收的参数是remove(Integer item),就是说如果我们传进来的参数是Integer类型的,那么就会调用这个删除指定元素的方法。而还有一个remove(int item)这个方法接收的参数是int类型的,和它最匹配的是一个int参数。在前面的代码里我们传进来的参数就是直接的一个int,所以和它最匹配的那个就是删除指定索引的那个。



package overload.special;

public class OverLoadTest {
	
	public void test(Object obj){
		System.out.println("Object:"+obj);
	}
	
	public void test(Integer integer){
		System.out.println("Integer:"+integer);
	}
	
	public void test(int int1){
		System.out.println("int:"+int1);
	}
	
	public void test(String str){
		System.out.println("String:"+str);
	}
	
	public static void main(String[] args) {
		OverLoadTest ot=new OverLoadTest();
		ot.test(1);
		ot.test("1");
	}
}

输出:
int:1
String:1

===》
优先级:
基本类型>对象
对象中 子类>父类,其中Object类的优先级最低


4 楼 frank-liu 2014-07-04  
793059909 写道
重载有优先级?
837062099 写道
重载方法中,调用优先级最高的是最精确的方法。

这样的重载,确实很容易是调用者发生错误,以前我自己写的这样的方法,找了好久才发现这个错误。


因为在这里remove方法接收的参数是remove(Integer item),就是说如果我们传进来的参数是Integer类型的,那么就会调用这个删除指定元素的方法。而还有一个remove(int item)这个方法接收的参数是int类型的,和它最匹配的是一个int参数。在前面的代码里我们传进来的参数就是直接的一个int,所以和它最匹配的那个就是删除指定索引的那个。
3 楼 793059909 2014-07-04  
重载有优先级?
837062099 写道
重载方法中,调用优先级最高的是最精确的方法。

这样的重载,确实很容易是调用者发生错误,以前我自己写的这样的方法,找了好久才发现这个错误。

2 楼 lizhensan 2012-03-10  
void  method(int a)
void  method(Integer a)

这两个方法是重装的方法,调用时不一样的。

1 楼 837062099 2012-03-09  
重载方法中,调用优先级最高的是最精确的方法。

这样的重载,确实很容易是调用者发生错误,以前我自己写的这样的方法,找了好久才发现这个错误。

相关推荐

Global site tag (gtag.js) - Google Analytics