简体   繁体   English

Java Array Array of Arrays?

[英]Java ArrayList of Arrays?

I want to create a mutli dimensional array without a fixed size. 我想创建一个没有固定大小的mutli维数组。

I need to be able to add items of String[2] to it. 我需要能够添加String[2]项目。

I have tried looking at: 我试过看:

private ArrayList<String[]> action = new ArrayList<String[2]>();

but that doesn't work. 但这不起作用。 does anyone have any other ideas? 有没有人有任何其他想法?

Should be 应该

private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...

You can't specify the size of the array within the generic parameter, only add arrays of specific size to the list later. 您不能在generic参数中指定数组的大小,只能稍后将特定大小的数组添加到列表中。 This also means that the compiler can't guarantee that all sub-arrays be of the same size, it must be ensured by you. 这也意味着编译器无法保证所有子阵列的大小相同,必须由您确保。

A better solution might be to encapsulate this within a class, where you can ensure the uniform size of the arrays as a type invariant. 更好的解决方案可能是将其封装在一个类中,您可以在其中确保数组的统一大小作为类型不变量。

BTW. BTW。 you should prefer coding against an Interface. 你应该更喜欢对接口进行编码。

private ArrayList<String[]> action = new ArrayList<String[]>();

Should be 应该

private List<String[]> action = new ArrayList<String[]>();

Since the size of your string array is fixed at compile time, you'd be better off using a structure (like Pair ) that mandates exactly two fields, and thus avoid the runtime errors possible with the array approach. 由于字符串数组的大小在编译时是固定的,因此最好使用一个强制要求两个字段的结构(如Pair ),从而避免使用数组方法可能出现的运行时错误。

Code: 码:

Since Java doesn't supply a Pair class, you'll need to define your own. 由于Java不提供Pair类,因此您需要定义自己的类。

class Pair<A, B> {
  public final A first;
  public final B second;

  public Pair(final A first, final B second) {
    this.first = first;
    this.second = second;
  }

  //
  // Override 'equals', 'hashcode' and 'toString'
  //
}

and then use it as: 然后将其用作:

List<Pair<String, String>> action = new ArrayList<Pair<String, String>>();

[ Here I used List because it's considered a good practice to program to interfaces. [这里我使用List因为它被认为是编程接口的好习惯。 ] ]

As already answered, you can create an ArrayList of String Arrays as @Péter Török written; 正如已经回答的那样,您可以创建一个字符串数组的ArrayList,如@PéterTörök所写;

    //Declaration of an ArrayList of String Arrays
    ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

When assigning different String Arrays to this ArrayList, each String Array's length will be different. 为此ArrayList分配不同的String Arrays时,每个String Array的长度都不同。

In the following example, 4 different Array of String added, their lengths are varying. 在以下示例中,添加了4个不同的String数组,其长度各不相同。

String Array #1: len: 3
String Array #2: len: 1
String Array #3: len: 4
String Array #4: len: 2

The Demonstration code is as below; 演示代码如下;

import java.util.ArrayList;

public class TestMultiArray {

    public static void main(String[] args) {
        //Declaration of an ArrayList of String Arrays
        ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

        //Assignment of 4 different String Arrays with different lengths
        listOfArrayList.add( new String[]{"line1: test String 1","line1: test String 2","line1: test String 3"}  );
        listOfArrayList.add( new String[]{"line2: test String 1"}  );
        listOfArrayList.add( new String[]{"line3: test String 1","line3: test String 2","line3: test String 3", "line3: test String 4"}  );
        listOfArrayList.add( new String[]{"line4: test String 1","line4: test String 2"}  );

        // Printing out the ArrayList Contents of String Arrays
        // '$' is used to indicate the String elements of String Arrays
        for( int i = 0; i < listOfArrayList.size(); i++ ) {
            for( int j = 0; j < listOfArrayList.get(i).length; j++ )
                System.out.printf(" $ " + listOfArrayList.get(i)[j]);

            System.out.println();
        }

    }
}

And the output is as follows; 输出如下;

 $ line1: test String 1 $ line1: test String 2 $ line1: test String 3
 $ line2: test String 1
 $ line3: test String 1 $ line3: test String 2 $ line3: test String 3 $ line3: test String 4
 $ line4: test String 1 $ line4: test String 2

Also notify that you can initialize a new Array of Sting as below; 还要通知您可以初始化一个新的Sting数组,如下所示;

new String[]{ str1, str2, str3,... }; // Assuming str's are String objects

So this is same with; 所以这是一样的;

String[] newStringArray = { str1, str2, str3 }; // Assuming str's are String objects

I've written this demonstration just to show that no the ArrayList object, all the elements are references to different instantiations of String Arrays, thus the length of each String Arrays are not have to be the same, neither it is important. 我写这个演示只是为了表明没有ArrayList对象,所有元素都是对String Arrays的不同实例的引用,因此每个String Arrays的长度不必相同,也不重要。

One last note : It will be best practice to use the ArrayList within a List interface, instead of which that you've used in your question. 最后一点 :最佳实践是在List接口中使用ArrayList,而不是您在问题中使用的那个。

It will be better to use the List interface as below; 最好使用List接口,如下所示;

    //Declaration of an ArrayList of String Arrays
    List<String[]> listOfArrayList = new ArrayList<String[]>();
ArrayList<String[]> action = new ArrayList<String[]>();

不需要String[2] ;

This works very well. 这非常有效。

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be 结果将是

Borkala
  1. Create the ArrayList like ArrayList action . ArrayList action一样创建ArrayList action

    In JDK 1.5 or higher use ArrayList <string[]> reference name. 在JDK 1.5或更高版本中使用ArrayList <string[]>引用名称。

    In JDK 1.4 or lower use ArrayList reference name. 在JDK 1.4或更低版本中使用ArrayList引用名称。

  2. Specify the access specifiers: 指定访问说明符:

    • public, can be accessed anywhere 公共,可以随处访问
    • private, accessed within the class 私人,在课堂上访问
    • protected, accessed within the class and different package subclasses 在类和不同的包子类中访问受保护的
  3. Then specify the reference it will be assigned in 然后指定它将被分配的引用

     action = new ArrayList<String[]>(); 
  4. In JVM new keyword will allocate memory in runtime for the object. 在JVM中, new关键字将在运行时为对象分配内存。

    You should not assigned the value where declared, because you are asking without fixed size. 您不应该在声明的位置分配值,因为您要求的是没有固定大小的值。

  5. Finally you can be use the add() method in ArrayList. 最后,您可以在ArrayList中使用add()方法。 Use like 用得像

     action.add(new string[how much you need]) 

    It will allocate the specific memory area in heap. 它将在堆中分配特定的内存区域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM