import java.util.ArrayList;<br />import java.util.List;<br />import java.util.Random;<br />public class UnSeqRandomNumber {<br /> private int min;<br /> private int max;<br /> public UnSeqRandomNumber() {<br /> this.min = 0;<br /> this.max = 10;<br /> }<br /> public UnSeqRandomNumber(int min, int max) {<br /> this();<br /> if (max > min) {<br /> this.min = min;<br /> this.max = max;<br /> } else<br /> System.out.println("max比min小,按預設的值產生UnrepeatRandomMumber對象!");<br /> }<br /> // 第一種方法:排除法.隨機產生數字,如果是新產生的數字則放到結果集中<br /> // 否則不採取行動<br /> public Integer[] getRandomA(int length) {<br /> if (length <= 0) {<br /> System.out.println("數字長度小");<br /> return new Integer[0];<br /> } else if (length > (this.max - this.min)) {<br /> System.out.println("結果清單長度達不到要求:" + length + "結果只能是:" + (this.max - this.min));<br /> length = this.max - this.min;<br /> }<br /> Random rand = new Random();<br /> List<Integer> list = new ArrayList<Integer>();<br /> while (list.size() < length) {<br /> Integer randnum = new Integer(this.min + rand.nextInt(this.max - this.min + 1));<br /> if (!list.contains(randnum)) {<br /> list.add(randnum);<br /> }<br /> }<br /> return (Integer[]) list.toArray(new Integer[0]);<br /> }<br /> public static void outputArray(Integer[] array) {<br /> if (array != null) {<br /> for (int i = 0; i < array.length; i++) {<br /> System.out.println(array[i] + " ");<br /> }<br /> }<br /> System.out.println();<br /> }<br /> public static void main(String[] args) {<br /> // TODO Auto-generated method stub<br /> UnSeqRandomNumber test = new UnSeqRandomNumber(5, 35);<br /> outputArray(test.getRandomA(100));<br /> }<br />}<br />