在2D LinkedList中添加一行

时间:2015-10-08 05:53:20

标签: java linked-list

从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;
    }
..............................
.............................
}

1 个答案:

答案 0 :(得分:0)

您需要初始化myBoard,因为您要声明它,但不能初始化为任何内容,因此其值为null。

您可以使用

初始化它
private LinkedList<LinkedList<T>> myBoard = new LinkedList<LinkedList<T>>();

或者,如果使用java 7或更新版本,您可以使用菱形运算符来简化它

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