如何从ArrayList <string []> </string []>获取值

时间:2014-01-12 11:01:54

标签: java

如何从ArrayList<String[]>获取或打印字符串?

ArrayList<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"A1","A1","A3"});
arrayList.add(new String[]{"B1","B1","B3"});
arrayList.add(new String[]{"C1","C1","C3"});

System.out.println("*** 1 ***");
System.out.println(arrayList);

System.out.println("*** 2 ***");
for (int i = 0; i < arrayList.size(); i++) {
    System.out.println((String[])arrayList.get(i));
}

System.out.println("*** 3 ***");
for (int i = 0; i < arrayList.size(); i++) {
    System.out.println(arrayList.get(i).toString());
}

System.out.println("*** 4 ***");
for (int i = 0; i < arrayList.size(); i++) {
    String[] strings = arrayList.get(i);
    System.out.println(strings);
}

输出:

*** 1 ***
[[Ljava.lang.String;@2a85f3d6, [Ljava.lang.String;@404b7c69, [Ljava.lang.String;@1bd4f279]

*** 2 ***
[Ljava.lang.String;@2a85f3d6
[Ljava.lang.String;@404b7c69
[Ljava.lang.String;@1bd4f279
*** 3 ***
[Ljava.lang.String;@2a85f3d6
[Ljava.lang.String;@404b7c69
[Ljava.lang.String;@1bd4f279
*** 4 ***
[Ljava.lang.String;@2a85f3d6
[Ljava.lang.String;@404b7c69
[Ljava.lang.String;@1bd4f279

3 个答案:

答案 0 :(得分:5)

可悲的是,java对数组的默认toString()是没用的。您必须使用实用程序方法Arrays.toString()。这将有效:

for (String[] strings : arrayList)
    System.out.println(Arrays.toString(strings));

答案 1 :(得分:2)

在Java中,每个对象都有toString()方法,默认显示类名表示,然后添加@,然后添加哈希码。

stringsString数组。您应该使用已Arrays#toString()实施的this way(我建议您通过它来更好地了解正在发生的事情):

3860     public static String toString(int[] a) { {
3861        if (a == null)
3862            return "null";
3863        int iMax = a.length - 1;
3864        if (iMax == -1)
3865            return "[]";
3866
3867        StringBuilder b = new StringBuilder();
3868        b.append('[');
3869        for (int i = 0; ; i++) {
3870            b.append(a[i]);
3871            if (i == iMax)
3872                return b.append(']').toString();
3873            b.append(", ");
3874        }
3875    }

或者,您可以循环并手动打印项目:

for(String str: strings) {
    System.out.println(str + " ");
}

答案 2 :(得分:0)

尝试修改此内容:

**@Override
public String toString() {
    return "abc [name=" + name + ", stage=" + stage
            + ", messageCode=" + messageCode + ", title=" + title
            + ", description=" + description + ", expiryTimeLeft="
            + expiryTimeLeft + ", holdLimit=" + holdLimit + ", points="
            + points];
}