java 数组去重总结

如果一个数组中有重复元素,用什么方法可以去重?有其他方法继续更新

一.用List集合实现

1  int[] str = {5, 6, 6, 6, 8, 8, 7,4};
2     List<Integer> list = new ArrayList<Integer>();    
3     for (int i=0; i<str.length; i++) {    
4         if(!list.contains(str[i])) {    
5             list.add(str[i]);    
6         }    
7     }    
8     System.out.println("去除重复后的list集合"+list);

 

输出结果是: 

去除重复后的list集合[5, 6, 8, 7, 4] 
可以看到可以去除重复的元素,但是没有实现排序功能。

二、输出数组中只出现一次的元素

 1 public class quchong {
 2     public static void main(String[] args) {
 3         int[] arr = new int[] { 1, 2, 3, 4, 5, 1, 2, 3, 2 };
 4         method(arr);
 5     }
 6 
 7     public static void method(int[] arr) {
 8         for (int i = 0; i < arr.length; i++) { //遍历数组
 9             boolean flag = true;  //定义一个标记
10             for (int j = 0; j < arr.length; j++) { 
11                 if (j == i) {
12                     continue;  // 如果和自己遍历则跳出当前循环,继续下一次循环。
13                 }  //如果外循环的元素只要有一个与内循环的元素相等,标记为false,不输出
14                 if (arr[i] == arr[j]) {
15                     flag = false;  
16                 }
17             }
18             //输出所有没被标记的元素,即为只出现一次的元素
19             if (flag) {
20                 System.out.println(arr[i]);
21             }
22         }
23     }
24 }

 

posted @ 2017-07-31 15:55  woa糊涂虫  阅读(1677)  评论(0编辑  收藏  举报