Day_12【集合】扩展案例1_利用集合的知识对长度为10的int数组进行去重,产生新数组,不能改变数组中原来数字的大小顺序

分析以下需求,并用代码实现

  • 1.定义一个长度为10的int数组,并存入10个int类型的数据,其中有一些数据是重复的
    2.利用集合的知识对数组进行去重,产生新数组,不能改变数组中原来数字的大小顺序
    3.打印新数组中的内容按照以下描述完成类的定义。
    

代码

package com.itheima;

import java.util.ArrayList;

public class Test1 {
	public static void main(String[] args) {
		// 定义一个长度为10的int数组,并存入10个int类型的数据,其中有一些数据是重复的
		int[] arr = { 5, 7, 8, 4, 5, 6, 3, 4, 8, 7 };

		// 利用集合的知识对数组进行去重,产生新数组,不能改变数组中原来数字的大小顺序

		// 创建集合对象
		ArrayList<Integer> array = new ArrayList<Integer>();
		// 遍历数组
		for (int in : arr) {
			// 判断集合中是否包含指定元素
			if (!array.contains(in)) {
				array.add(in);
			}
		}
		// 定义新数组
		int[] newArr = new int[array.size()];
		
		//定义新集合的索引
		int index = 0;
		for (int in : array){
			newArr[index++] = in;
		}

		for(int i = 0;i < newArr.length;i++){
			System.out.println(newArr[i]);
		}
	}

}

控制台内容
console

原文地址:https://www.cnblogs.com/zzzsw0412/p/12772526.html