你可以实现自己的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