遍歷ArrayList對象remove掉不需要的元素

1.從test中移除值爲“i am 2”的元素

@Test
public void testHaha() {
    List<String> test = new ArrayList<String>();
    test.add("i am 1");
    test.add("i am 2");
    test.add("i am 2");
    for (String string : test) {
        if (string.equals("i am 2")) {
            test.remove(string);
        }
    }
    for (String string : test) {
        System.out.println(string);
    }
}
運行結果:

i am 1
i am 2

索引爲3的元素遍歷時漏掉了沒有被遍歷

解決方法一:從最後一個元素開始遍歷

@Test
public void testHaha() {
	List<String> test = new ArrayList<String>();
	test.add("i am 1");
	test.add("i am 2");
	test.add("i am 2");
	for (int i = test.size(); i > 0; i--) {
		String string = "i am 2";
		if (string.equals(test.get(i-1))) {
			test.remove(i-1);
		}
	}
	for (String string : test) {
		System.out.println(string);
	}
}
解決方法二:移除一個元素後把i減1,使所有的元素都被遍歷到

@Test
public void testHaha() {
	List<String> test = new ArrayList<String>();
	test.add("i am 1");
	test.add("i am 2");
	test.add("i am 2");
	for (int i = 0; i < test.size(); i++) {
		String string = "i am 2";
		if (string.equals(test.get(i))) {
			test.remove(i--);
		}
	}
	for (String string : test) {
		System.out.println(string);
	}
}





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