简体   繁体   English

创建一个ArrayList数组<String>元素

[英]Create an array of ArrayList<String> elements

I want to create an array that contains ArrayList<String> elements.我想创建一个包含 ArrayList<String> 元素的数组。

I've tried我试过了

ArrayList<String> name[] = new ArrayList<String>()[];

but that doesn't seem to work.但这似乎不起作用。

You cannot create an array of a generic type.您不能创建泛型类型的数组。

Instead, you can create an ArrayList<ArrayList<String>> .相反,您可以创建一个ArrayList<ArrayList<String>>

The correct way is:正确的方法是:

ArrayList<String> name[] = new ArrayList[9];

However, this won't work either, since you can't make an array with a generic type, what you are trying to do is a matrix, and this should be done like this:但是,这也不起作用,因为您无法创建具有泛型类型的数组,您要做的是一个矩阵,这应该像这样完成:

String name[][];

I know this is a bit old but I am going to respond to this anyway for future views.我知道这有点旧,但无论如何我都会对此做出回应以供将来查看。

If you really want an ArrayList<String>[] structure, you can simply create a class that extends ArrayList and make an array of that class:如果你真的想要一个ArrayList<String>[]结构,你可以简单地创建一个扩展 ArrayList 的类并创建一个该类的数组:

public class StringArrayList extends ArrayList<String>{}

And in your implementation:在您的实施中:

ArrayList<String> name[] = new StringArrayList[9];

Here is a sample:这是一个示例:

package testspace.arrays;

import java.util.List;

public class TestStringArray {

    public static void main(String[] args) {
        List<String>[] arr = new StringArrayList[10];
        for(int i = 0; i < arr.length; i++){
            // CANNOT use generic 'new ArrayList<String>()'
            arr[i] = new StringArrayList(); 
            for(int j = 0; j < arr.length; j++){
                arr[i].add("list item #(" + j + "|" + i + ")");
            }
        }

        StringBuilder sb = new StringBuilder();
        for(final List<String> list : arr){
            for(final String str : list){
                sb.append(str + " ");
            }
            sb.append("\n");
        }
        System.out.println(sb.toString());
    }

}

NOTE You will get a runtime error if you use this instead : arr[i] = new ArrayList<String>()注意如果你使用它,你会得到一个运行时错误: arr[i] = new ArrayList<String>()

This is not proper OO and this sort of code is very implementation coupled.这不是正确的 OO,而且这种代码是非常耦合的。 If you need to do such thing, probably you did something wrong.如果你需要做这样的事情,很可能你做错了什么。 If the code is not yours, the person who made it probably did something wrong.如果代码不是你的,那么制作它的人可能做错了什么。

If you know how many elements are there (or even if you didn't), why not use Map<Integer,List<String>> ?如果您知道有多少元素(或者即使您不知道),为什么不使用Map<Integer,List<String>>

ArrayList<ArrayList<String>> name= new ArrayList<ArrayList<String>>(/*capacity*/);

If you do want an array of ArrayList , you'll have to initialise each position of the array individually:如果您确实想要一个ArrayList ,则必须单独初始化数组的每个位置:

int size = 9; // 9 is just an example
// you can remove the annotation, but you'll be warned:
// Type safety: The expression of type ArrayList[] needs unchecked conversion 
// to conform to ArrayList<String>[]
@SuppressWarnings("unchecked")
ArrayList<String> name[] = new ArrayList[ size];
for( int i = 0; i < size; i++) {
    name[ i] = new ArrayList<String>();
}

I have tried this without an error, even though I have putted a limit in the array less than the amount of items added:我试过这个没有错误,即使我在数组中设置的限制少于添加的项目数量:

package Testes.src;

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

public class Testes {

    private List<String> name=new ArrayList<String>(1);

    public Testes(){
        for (int i = 1; i <= 100; i++) {
            name.add("Teste"+Integer.toString(i));
        }
        for (int i = 0; i < name.size(); i++) {
            System.out.println(name.get(i));
        }
    }
    public static void main(String [] args)
    {
        Testes t1=new Testes();
    }
}

I know this is an old post, but someone just asked the same question and since nobody has mentioned the following solution, here it is.我知道这是一个旧帖子,但有人问了同样的问题,因为没有人提到以下解决方案,所以在这里。

One way to get around it could be something like a 2d array (the recent question was about a 2d array or ArrayLists) of objects and then you should be able to put ArrayList references in the array.绕过它的一种方法可能是对象的二维数组(最近的问题是关于二维数组或 ArrayLists),然后您应该能够将 ArrayList 引用放入数组中。 I have not tested it, but something like this should work.我还没有测试过,但这样的事情应该可以工作。

Object [][] data = new Object[5][5];
data[0][0] = new ArrayList<String>(); // etc . . .

You may try this:你可以试试这个:

ArrayList[] arr=new ArrayList[5];
for(int i=0;i<5;i++)
     arr[i]=new ArrayList<String>();
arr[1].add("35");
arr[1].add("ME");
arr[1].add("HELLO");
System.out.println(arr[1]);

Output:输出:

[35, ME, HELLO]
// This is the not correct way
ArrayList<String> name[] = new ArrayList<String>()[];

// This is the correct way
ArrayList<String> list[] = new ArrayList[2];

list[0] = new ArrayList();
list[1] = new ArrayList();

list[0].add("Some String 11");
list[0].add("Some String 22");

list[1].add("Some String 1111");
list[1].add("Some String 2222");

Array of ArrayLists, example with Loops ArrayLists 数组,循环示例

//Declare
Object[] arrayLists = new Object[size];    

//Fill
for (int j=0; j < size; j++) {
     arrayLists[k]= generateAnArrayList(j);  //or whatnot
}

//Usage
for (int j=0; j < size; j++) {
    ArrayList<Long> al = (ArrayList<Long>) arrayLists[j];
    //do something here
}

There is a way to do it with only little modification of your code.有一种方法可以只对代码进行少量修改。

ArrayList<String>[] name = new ArrayList[10]; 

This will give you a array of ArrayList.这将为您提供一个 ArrayList 数组。

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

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