2016-09-27 125 views
-3

我想創建的ArrayList ArrayList和投入要素的孩子在父母的具體指標,反之亦然..請任何暗示如何將元素添加到arraylist的arraylist?

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

public class vertexCover { 

    int n; 
    static ArrayList<ArrayList<Integer>> arr = new ArrayList<>(); 
    static int s, e; 

    public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 
     int n = sc.nextInt(); 
     for (int i = 0; i <= n; i++) { 
      int s = sc.nextInt(); 
      int e = sc.nextInt(); 
      ArrayList temp = new ArrayList(); 
      ArrayList temp2 = new ArrayList(); 
      temp.add(e); 
      arr.add(s, temp); 
      temp2.add(s); 
      arr.add(e,temp2); 
     } 
     for (int i = 0; i <= arr.size(); i++) { 
      for (int x = 0; x <= 5; x++) { 
       System.out.println(arr.get(i).get(x)); 
      } 
     } 
    } 
} 
+0

在這裏看到更好的指導增加100指數:http://stackoverflow.com/questions/16956720/how-to-create-an-2d-arraylist-in-java – px06

+0

它們是:'ArrayList的臨時=新的ArrayList();'。儘管這也是一個相關的鏈接。 – Tunaki

+0

@Tunaki是的,我剛纔看到的,但我認爲他在做什麼,而不是試圖使用原始類型更加困惑。 – px06

回答

0

好像你正在尋找類似的HashMap來ArrayList的東西。

試試這個:

ConcurrentHashmap <Integer,ArrayList<Your type>> map = new ConcurrentHashmap<>(); 

爲了把值:map.put(1, your array list)

中獲取價值:map.get(1);

這種方法將在相同的方式工作,你正在尋找。

待辦事項:get()方法將使用散列碼來獲取價值,而不是它的索引。

還要注意:根據Java API的https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int,%20E)你不能添加元素比列表大小大的索引。這意味着你不能沒有填充第99個指數