我需要从2D T [] [] x复制每个值到2D LinkedList。我的代码在这一行给了我错误:

 myBoard.addAll((Iterable<AdditiveList<T>>) newLine);


通过抛出NullPointerException
我的LinkedList类具有方法addAll(Iterable<T> c)。如何将整条线添加到2D列表中?

类别Tester

public class Tester {

    public static void main(String[] args){
         Integer mat [][] = {
                  { 1, 2, 3, 0},
                  { 0, 0, 0, 0},
                  { 4, 0, 5, 6},
                };
                Integer fill = new Integer(0);
        SparseBoard<Integer> myBoard = new SparseBoard<Integer>(mat, fill);
        String s = myBoard.createBoard();
        System.out.println(s);
    }
}


类别Board

public class Board<T> {
   private LinkedList<LinkedList<T>> myBoard = new LinkedList<LinkedList<T>>(); //Initialized inside constructors

     public Board(T[][] x, T fillElem){
          LinkedList<T> newLine;
          for(int i = 0; i < x.length; i++){
              newLine = new LinkedList<T>();
            //Iterator<T> iter =
              myBoard.addAll((Iterable<AdditiveList<T>>) newLine);// <<<<-------- getting error here
              for(int j = 0; j < x[i].length; j++){
                  newLine.add(j, x[i][j]);
              }
          }
      }


类别LinkedList

public class LinkedList<T> implements Iterable<T>{

    // Doubly-linked list node for use internally
    public static class Node<T> {

        public T data;
        public Node<T> prev, next;

        public Node(T d, Node<T> p, Node<T> n) {
            this.data = d;
            this.prev = p;
            this.next = n;
        }

        public Node(T d){
            this.data = d;
        }
    }
.......................................
.......................................
public void add( int idx, T x ){
        Node<T> p = getNode( idx, 0, size( ) );
        Node<T> newNode = new Node<T>( x, p.prev, p );
        newNode.prev.next = newNode;
        p.prev = newNode;
        theSize++;
}
public boolean addAll(Iterable<T> c){
        boolean added = false;
        for(T thing : c){
            added |= this.add(thing);
        }
        return added;
    }
..............................
.............................
}

最佳答案

您需要在声明时初始化myBoard,但不初始化为任何东西,因此其值为null。

您可以使用

private LinkedList<LinkedList<T>> myBoard = new LinkedList<LinkedList<T>>();


或者,如果使用的是Java 7或更高版本,则可以使用菱形运算符将其简化

private LinkedList<LinkedList<T>> myBoard = new LinkedList<>();

关于java - 在2D LinkedList中添加一条线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33007635/

10-12 04:50