你可以實現自己的List類。爲此,您應該定義一個Node,一個List類(將包含節點)和一個負責創建隨機數的服務。
此服務將以單例表示(不能由任何其他類實例化的類)。
public class MyRandom {
private static MyRandom rdn = new MyRandom();
private MyRandom() {}
public static MyRandom getInstance() {
return rdn;
}
public int getRandom(int min, int max) {
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
該節點將只包含一個值(隨機數)和對下一個節點的引用。這是節點類
public class MyNode {
private final int value;
private MyNode next;
public MyNode(int value) {
this.value = value;
next = null;
}
public void setNext(MyNode next) {
this.next = next;
}
public int getValue() {
return value;
}
public MyNode getNext() {
return next;
}
}
List類將包含對根節點的引用,它也將負責將新節點添加到列表中。
請記住,您也可以使用泛型。
public final class MyList {
private MyNode root;
public MyList(int maxNumber) {
for (int i = 0; i < maxNumber; i++) {
addNode(MyRandom.getInstance().getRandom(0, 99));
}
}
public boolean isEmpty() {
return root == null;
}
public void addNode(int value) {
if (isEmpty()) {
root = new MyNode(value);
} else {
MyNode aux = root;
while (aux.getNext() != null)
aux = aux.getNext();
aux.setNext(new MyNode(value));
}
}
public void printList() {
if (!isEmpty()) {
MyNode aux = root;
while (aux.getNext() != null) {
System.out.println(aux.getValue());
aux = aux.getNext();
}
System.out.println(aux.getValue());
}
}
}
和主只能實例化MYLIST類並調用的printList顯示列表。
public class Main {
public static void main(String[] args) {
MyList lista = new MyList(10);
lista.printList();
}
}
希望這可以幫助你。
這不是真的OOP ... – Tdorno