![](/img/trans.png)
[英]why list can't be initialized with array, without arrays.aslist()?
[英]How can I convert an array to a list without using Arrays.asList() method or Java List Interface
我得到了我的Node
类:
public class Node <T> {
private Node<T> next;
private T element;
public void setElement(T element) {
this.element = element;
}
public T getElement() {
return element;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node <T> next) {
this.next= next;
}
}
而且我还有我的List
类:
public class List <T> {
Node<T> first;
Node<T> last;
...在它上面我可以做各种事情,比如向我的列表添加元素或替换它们、删除一些元素、查看我的列表的大小等。这些方法的一个例子是addFirst()
。
public T addFirst(T element) {
Node<T> aux;
if (isEmpty()) {
aux = new Node<>();
first= aux;
lsat= aux;
aux.setElement(element);
} else {
aux = new Node<>();
aux.setElement(element);
aux.setNext(first);
first= aux;
}
return first.getElement();
}
我只缺少一种方法,显然具有前面提到的限制将数组转换为列表。
您应该使用 for 循环遍历数组。 并在每次迭代中调用addFirst()
函数。
Node a[] = new Node[]{node1,node2,node3,node4};
for (int i=0; i<a.length; i++) {
yourListObject.addFirst(a[i]);
}
一种解决方案是遍历数组并简单地填充List
:
// your array of Nodes
Node<?>[] nodeArray = new Node[]{node1,node2,node3,node4,node5};
// your List
List<?> myList = new List<>();
for(Node<?> node : nodeArray)
{
myList.addLast(node); // use addLast() to keep the same order as the array
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.