/** * 定义一个数组 */ private static Object[] arr = {}; public static void main(String[] args) { for (int i = 0; i < 10; i++) { Integer id = getRandomId(); System.out.println("获取对应的主键:"+id); } } /** * 从数组中任意获取主键ID */ private static Integer getRandomId() { Integer result = 0; if (arr.length==0) { arr = getArray(); } int index = (int) (Math.random()*arr.length); result = (Integer) arr[index]; arr = removeArr(arr, index); return result; } /** * 从数组中移除获取对应的主键 */ public static Object[] removeArr(Object[] arr,int index){ List<Integer> list = new ArrayList<Integer>(); for (Object num : arr) { list.add((Integer) num); } list.remove(index); return list.toArray(); } /** * 往数组中放入 1000 个主键ID */ private static Object[] getArray() { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 1000; i++) { list.add(i); } return list.toArray(); }