第六题:
- package com.itheima;
- import java.util.Arrays;
- import java.util.LinkedHashSet;
- /*
- * 第六题:数组去重复,例如: 原始数组是{4,2,4,6,1,2,4,7,8},得到结果{4,2,6,1,7,8}
- *
- * 分析:
- * LinkedHashSet集合有序且唯一,用来接收原始数组,把集合再转为数组就可以了
- */
- public class Test6 {
- public static void main(String[] args) {
- int[] arr = { 4, 2, 4, 6, 1, 2, 4, 7, 8 };
- // 创建集合接受新的数组
- LinkedHashSet<Integer> newArr = new LinkedHashSet<Integer>();
- // 集合中不包含就添加进去
- for (int i : arr) {
- newArr.add(i);
- }
- // 创建一个长度为集合长度的数组
- Integer[] i = new Integer[newArr.size()];
- // 集合转为数组
- newArr.toArray(i);
- // 输出数组
- System.out.println(Arrays.toString(i));
- }
- }
复制代码
|