我是靠谱客的博主 沉默小蘑菇,最近开发中收集的这篇文章主要介绍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;
		}
	}
}


最后

以上就是沉默小蘑菇为你收集整理的ArrayList、Iterator的remove方法的全部内容,希望文章能够帮你解决ArrayList、Iterator的remove方法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部