作为常用的数据结构,List经常被我们用到,以ArrayList为例,本文主要介绍其contains()和remove()方法。
假设有以下数据结构:
class Int {
private int id;
public Int(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString(){
return this.id + "";
}
}
List<Int> aList = new ArrayList();
aList.add(new Int(10));
aList.add(new Int(11));
aList.add(new Int(3));
List<Integer> bList = new ArrayList();
bList.add(2);
bList.add(11);
bList.add(31);
现在需要将aList中id等于bList的数据同时从aList和bList中删除,可使用下面方法
for (int i = 0;i < aList.size();i++) {
if (bList.contains(aList.get(i).getId())) {
bList.remove(new Integer(aList.get(i).getId()));
aList.remove(i--);
}
}
System.out.println("aList : " + aList);
System.out.println("bList : " + bList);
输出结果为:
aList : [10, 3]
bList : [2, 31]
在上例中,使用到了List的contians()和remove()方法
在ArrayList的api中,contains()方法定义如下:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
从api中可以看出,contains()方法是将入参循环调用Object的equals()方法,在上文的例子中,由于int可自动装箱为Integer类型,而Integer的equals()已经重写,如果相比较的两个Integer对象的int的值相等则返回true,所以可用bList.contains(aList.get(i).getId())的方式来判断aList中的int类型值是否在bList中。
remove()方法定义如下:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
remove()使用了重载,既可以通过Object参数来删除,也可以通过ArrayList的下标来删除,所以在调用时需要注意,如果入参为int类型时,会造成调用remove(int index)方法而不是remove(Object o)导致无法自动装箱出错,可能会造成集合的引用越界问题,因此需要使用bList.remove(new Integer(aList.get(i).getId()))而不是bList.remove(aList.get(i).getId())