Java实现产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。

    public  static void main(String[] args){
        //创建一个int数组,长度为100,
        int n = 100;
        int[] arrayInt = new int[n];
        Random random = new Random();
        ArrayList myList = new ArrayList();
        while(myList.size() < 100){
            //随机函数生成0-100的整数
            int num = random.nextInt(101);
            //myList不包含则添加元素 去重
            if(!myList.contains(num) && num >0){
                myList.add(num);
            }
        }
        myList.sort(null);
        System.out.println(myList.size() + ",");
        //myList数组值赋值给int数组
        for(int i=0;i<100;i++){
            arrayInt[i] = (int)myList.get(i);
            System.out.println(arrayInt[i] + ",");
        }
    }

 大家可以用Integer数组试试,代码要少点:

//    ArrayList<Integer> myList = new ArrayList<Integer>();
//    Integer[] b = new Integer[myList.size()];//当泛型为Integer时,需要
//    arrayInt = (Integer[])myList.toArray(b);
原文地址:https://www.cnblogs.com/liuxiutianxia/p/9581476.html