Java数组去除重复元素

import java.util.LinkedList;
import java.util.List;
/*
 * 数组去重复,例如: 原始数组是{4,2,4,6,1,2,4,7,8},得到结果{4,2,6,1,7,8}
 */
public class RemoveTest {

    public static void main(String[] args) {
        String[] arr = {"4","2","4","6","1","2","4","7","8"};
        // 把数组存入set, set会自动去掉重复数字
/*        Set<String> set = new TreeSet<>();
        set.addAll(Arrays.asList(arr)); 
        System.out.println("去重复:");
        System.out.println("无序:"+set); // 但 Set是无序的
*/
        // 存入list,顺序排序
        List<String> list = new LinkedList<>();
        for (int i = 0; i < arr.length; i++) {
            if ( !list.contains(arr[i])) {
                list.add(arr[i]);
            }
        }// 用get方法取出list元素
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i)+" ");
        }
    }
}

 

posted @ 2008-09-15 21:17  蒋至乙  阅读(964)  评论(0编辑  收藏  举报