ArrayList去除集合中字符串的重复值,只能在本集合内操作


/*
* 需求:ArrayList去除集合中字符串的重复值,只能在本集合内操作
*
* 分析:
* 1.创建一个集合对象
* 2.添加多个字符串元素
* 3.用选择排序方法去比较
* A:如有相同的,则删除此元素
* B:没有,则保留
* 4.遍历输出 新集合
*/

package com.ma.arraylist;

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

/**
 * ArrayList去除集合中字符串的重复值,只能在本集合内操作
 * @author ma
 *
 */
public class ArrayListDemo2 {

	/*
	 * 需求:ArrayList去除集合中字符串的重复值,只能在本集合内操作 
	 * 
	 * 分析:
	 * 		1.创建一个集合对象
	 * 		2.添加多个字符串元素
	 * 		3.用选择排序方法去比较
	 * 			A:如有相同的,则删除此元素
	 * 			B:没有,则保留
	 * 		4.遍历输出 新集合
	 */
	
	public static void main(String[] args) {
		//1.创建一个ArrayList集合对象
		ArrayList arrList = new ArrayList();
		
		//2.添加多个字符串元素
		//向ArrayList添加字符串元素
		arrList.add("hello");
		arrList.add("world");
		arrList.add("hello");
		arrList.add("java");
		arrList.add("你好");
		arrList.add("世界");
		arrList.add("你好");
		arrList.add("爪哇");
		
		arrList.add("hello");
		arrList.add("hello");
		arrList.add("hello");
		arrList.add("hello");
		
		/*
		 * 	3.用选择排序方法去比较
		 * 		A:如有相同的,则删除此元素
		 * 		B:没有,则保留
		 */
		int aa=0;
		for (int i = 0; i < arrList.size() - 1; i++) {
			for (int j = i + 1; j < arrList.size(); j++) {
				if(arrList.get(i).equals(arrList.get(j))){
					arrList.remove(j);
					
					//因为有连续相同的元素,当月移除去j就变大了1,所以j要减1,再循环
					j--;
					
				}
				
			}
		}
		
		//4.遍历输出 新集合
		//得到迭代器
		Iterator it = arrList.iterator();		
		
		//遍历输出 新集合
		while (it.hasNext()) {
			String str = (String) it.next();
			System.out.println(str);
			
		}
		
	}
}

输出结果:

  hello
  world
  java
  你好
  世界
  爪哇

猜你喜欢

转载自www.cnblogs.com/majingang/p/9018973.html
今日推荐