集合框架-去重字串案例-2

ZHOU_VIP發表於2017-04-23

方法四:


package cn.itcast_04;

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

/*
 * 需求:ArrayList去除集合中字串的重複值(字串的內容相同)
 * 要求:不能建立新的集合,就在以前的集合上做。
 */
public class ArrayListDemo2 {
	public static void main(String[] args) {
		// 建立集合物件
		ArrayList array = new ArrayList();
   
		// 新增多個字串元素(包含內容相同的)
		array.add("hello");
		array.add("world");
		array.add("java");
		array.add("world");
		array.add("java");
		array.add("world");
		array.add("world");
		array.add("world");
		array.add("world");
		array.add("java");
		array.add("world");

		// 由選擇排序思想引入,我們就可以通過這種思想做這個題目
		// 拿0索引的依次和後面的比較,有就把後的幹掉
		// 同理,拿1索引...
		for (int x = 0; x < array.size() - 1; x++) {
			for (int y = x + 1; y < array.size(); y++) {
				if (array.get(x).equals(array.get(y))) {
					array.remove(y);
					y--;
				}
			}
		}

		// 遍歷集合
		Iterator it = array.iterator();
		while (it.hasNext()) {
			String s = (String) it.next();
			System.out.println(s);
		}
	}
}


相關文章