[英]Java ArrayList remove method polymorphism
即时通讯使用ArrayList<Integer>
,我注意到有两种删除方法:
从List
接口入侵的那个:
public boolean remove(Object o)
并且在ArrayList
实现了一个:
public Object remove(int index)
在我的情况下,当我打电话给list.remove(2);
,将调用哪种方法? 为什么? 因为我的“对象”也是整数...
谢谢。
public Object remove(int index)
将被召唤。
由于您正在调用list.remove(2)
,因此参数的类型为int。 因此,最具体的匹配值获得该呼叫,在这种情况下,法, remove(int index)
,并在值index
将被删除
如果你调用这样的方法:
intList.remove(2);
第二项将被删除。 如果你调用这样的方法:
intList.remove(new Integer(2)));
对象2将被删除。
从ArrayList.remove(Object obj)上的JavaDocs:
从此列表中删除指定元素的第一个匹配项(如果存在)。 如果列表不包含该元素,则不会更改。 更正式地,删除具有最低索引i的元素,使得(o == null?get(i)== null:o.equals(get(i)))(如果存在这样的元素)。 如果此列表包含指定的元素,则返回true(或等效地,如果此列表因调用而更改)。
因为它使用o.equals(),所以它要求A)中包含的元素是一个对象,而B)等于remove()参数。
这是一个演示样本。
/**
*
*/
package ksf;
import java.awt.List;
import java.util.ArrayList;
/**
* @author Kelly French
*
*/
public class ListRemove {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList l = new ArrayList();
l.add(new Integer(0)); // to take up the zeroth spot
l.add(new Integer(300)); // 1st added, position [1]
l.add(new Integer(100)); // 2nd added, position [2]
l.add(new Integer(200)); // 3rd added, position [3]
// will remove whatever is at location 2, i.e. Integer(100)
l.remove(2);
// will remove first object Integer(200) if it exists
// in this case it is the equivalent of l.remove(3);
l.remove(new Integer(200));
// will cause nothing to be removed
l.remove(200); // no 200th element in the list
l.remove(new Integer(2)); // no element passes o.equals()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.