ArrayList、Iterator的remove方法

package szsm;

import java.util.ArrayList;
import java.util.List;
/**
 * Removes the first occurrence of the specified element from this list,
 * if it is present.  If the list does not contain the element, it is
 * unchanged.  More formally, removes the element with the lowest index
 * <tt>i</tt> such that
 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
 * (if such an element exists).  Returns <tt>true</tt> if this list
 * contained the specified element (or equivalently, if this list
 * changed as a result of the call).
 *
 * @param o element to be removed from this list, if present
 * @return <tt>true</tt> if this list contained the specified element
 */
/**
 * ArrayList的remove(int index)方法
 * 
 * 源碼:
 * public E remove(int index) {
	RangeCheck(index);

	modCount++;
	E oldValue = (E) elementData[index];

	int numMoved = size - index - 1;
	if (numMoved > 0)
	    System.arraycopy(elementData, index+1, elementData, index,
			     numMoved);
	elementData[--size] = null; // Let gc do its work

	return oldValue;
    }
    
    
    
    private void RangeCheck(int index) {
	if (index >= size)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);
    }
 * @author 2萌
 *
 */
public class TestRemove {

	public static void main(String[] args) {
		List list = new ArrayList();
		for (int i = 0; i < 10; i++) {
			list.add(i);
		}
		System.out.println(".................");
		for (int i = 0; i < 5; i++) {
			System.out.println(list.remove(i));
		}
		System.out.println(".................");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}
}

ArrayList的remove方法

Iterator的remove方法

package szsm;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test {
	public static void main(String args[]) {
		List list = new ArrayList();
		for (int i = 1; i < 10; i++) {
			list.add(i);
		}
		
		Iterator iterator = list.iterator();
		
		while (iterator.hasNext()) {
			Integer obj = (Integer) iterator.next();
			
			if (needRemove(obj)) {
				/**
				 * 考點:考察iterator的remove()方法
				 * Iterator接口有三個方法:boolean hasNext();
				 *                    E next();
				 *                    void remove();
				 */
				
               iterator.remove();
			}
		}
		
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
		
	}

	public static boolean needRemove(Integer obj) {
		int object1 = obj;
		if (object1 %2 != 0) {
			return true;
		} else {
			return false;
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章