2014-02-16 90 views
1

它說我必須初始化adj但它不起作用。我知道有什麼大錯誤。我也嘗試在一個ArrayList中使用一個ArrayList,但也沒有工作。你覺得怎麼了?爲什麼我無法將節點添加到我的鄰接列表中?

import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 



public class AdjacencyList { 

    public static void main(String[] args) { 

     Scanner in = new Scanner (System.in); 
     System.out.println("Enter nodes below like (u,v):"); 

     //Create List 
     ArrayList<Integer>[] adj; 


     for (int i=0; i<2; i++) { 
      String nodes = in.nextLine(); 
      String[] data = nodes.split(","); 

      String u = data[0]; 
      String v = data[1]; 
      int inNode = Integer.parseInt(u); 
      int outNode =Integer.parseInt(v); 

      adj[inNode] = new ArrayList<Integer>(); 
      adj[inNode].add(outNode); 
      System.out.println("Added to list"); 

     } 

     //print nodes and then their corresponding list 
     System.out.println(adj[1]); 




    } 

} 
+0

'ArrayList的 []形容詞;'你確定你想要的'數組ArrayList's? – Maroun

+0

不,那太貴了,所以不在這個階段。 –

+1

但這就是你在做什麼。 – Maroun

回答

1

假設你真的想要一個ArrayList陣列S,你應該這樣初始化:

ArrayList<Integer>[] adj = (ArrayList<Integer>[]) new ArrayList[SIZE]; 
+1

類型不匹配。我需要在循環中迭代地爲每個唯一節點創建ArrayList,所以我正在做adj [inNode] =(ArrayList [])new ArrayList [2]; –

+0

你不應該在這行中得到* type mismatch *。您正在循環中初始化數組中的每個*元素。但是,您還需要初始化*數組*! – Maroun

+0

我做到了,不起作用。在循環初始化過程中會出現類型不匹配,這是原始問題。 –

相關問題