如何声明2D String arraylist?
我想做类似这个ArrayList<String> mylist
我该如何创建它?
如何添加到外部和内部列表
以及如何将内部列表转换为简单的数组列表?
你可以去
List> ls2d = new ArrayList>(); List x = new ArrayList (); x.add("Hello"); x.add("world!"); ls2d.add(x); System.out.println(Arrays.deepToString(ls2d.toArray()));
第一个数组列表不是String的数组列表,它是ArrayList的ArrayList。
ArrayList>
List> array = new ArrayList>(); ... array.add(new ArrayList ()) array.get(0).add("qqq");
array.get(0) – 是一个内部列表
List> super2dArray = new ArrayList>()
这是一个拿着弦乐的arraylists的arraylist。
另外ArrayList
没有意义,因为String不是一个集合/列表,但我想你明白了。 未来的读者可能不会。
看到这个答案 ,看看为什么我选择在左侧有List
。
尝试这个 :
public class JavaTests { /** * @param args the command line arguments */ public static void main(String[] args) { String[ ][ ] test2 = new String[3][3]; //3 can be replace if you add more test2[?][?] = "RandomString" test2[0][0] = "String1"; test2[0][1] = "String2"; test2[0][2] = "String3"; test2[1][0] = "String4"; test2[1][1] = "String5"; test2[1][2] = "String6"; test2[2][0] = "String7"; test2[2][1] = "String8"; test2[2][2] = "String9"; for (int i = 0; i <= 2; i++){ for (int j = 0; j <= 2; j++){ System.out.print(test2[i][j] +"\t"); } System.out.println("\n"); } System.out.println("\n"); } }
有两种方法可以实现您的愿望。 我正在为两者提供代码片段:
1. List
> lol = new ArrayList
Scanner in = new Scanner(System.in); int size = in.nextInt(); //Declare your two dimensional ArrayList of Strings. List< List> lol = new ArrayList>(); //Instantiate and Populate for (int i=0;i()); for (int j=0;j
2. ArrayList[] set = new ArrayList[n];
Scanner in = new Scanner(System.in); int size = in.nextInt(); //Declare your two dimensional ArrayList of Strings. ArrayList[] set = new ArrayList[size]; //Populate it. for(int i=0;i(); for(int j=0;j