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);
