首页 > 解决方案 > 如何避免在 Java 中由 math.random 数字创建的数组中创建重复项?

问题描述

我有一个方法可以创建一个长度由 Main 中的参数决定的数组。这些数字是由数学随机创建的。如何通过在每次将其放入数组之前检查创建的随机数来避免重复?

是否可以检查未完成的数组?

class Test{
        public int[] numberArray;
        public int length;


    public Test(int lengthArray){
        this.numberArray=new int[lengthArray];
        this.length=lengthArray;
    }


    public boolean checkArray(int checknumber){
    inArray=false;

             //what code can I write here to find duplicate

        return inArray;
    }


    public void fillArray(){
        int highest = 1000;
        int lowest = 100;
        int randomNumber = 0;
        int counter=0;


        for(int i=0;i<length;i++){
            randomNumber=lowest + (int)(Math.random() * ((highest - lowest) + 1));
            numberArray[counter]=randomNumber;
            counter++;



          }
}

public class testing {
    public static void main(String[] args) {

    Test test1 = new Test(9);
    test1.fillArray();
            for(int value: test1.numberArray){
        System.out.print(value+" ");
}
    }
    }

标签: javaarraysduplicates

解决方案


您可以首先创建所需的所有数字并将其存储在 Set 数据结构中,直到大小等于您想要的数字数量。稍后,将 Set 中的所有数字转移到一个相同大小的数组中


推荐阅读