0

在 Python 中,我可以做一些简单的事情,例如:

# declare lists
A =["a","bnbnb"]
B = [1,2,3]
C = ['x'] + A    # (Simple Append)

# iterate over both lists
for x in [A,B,C]:  # (Create list of lists on the fly for for loops)
    do something to X[0]

等等。

我是 Java 新手 - 并且了解数组是固定大小的,但列表和数组列表不是。我将如何模仿上述内容?

这是我失败的尝试

# declare lists
String[] A ={"a","bnbnb"}
String[] B = [1,2,3]
Stuck here C = ['x'] + A    (Simple Append)

# iterate over both lists
for x in [A,B,C]:  (Cant seem to do this either)
    # do something to X[0]

使用ArrayLists 只会让它变得更加麻烦 - 我打赌我错过了一些明显的东西。

4

2 回答 2

2

你应该使用Lists 代替:

List<String> A = Arrays.asList("a", "bnbnb");
List<String> B = Arrays.asList("1", "2", "3");

// you have to do this in two steps:
List<String> C = new ArrayList<String>(Arrays.asList("x"));
C.addAll(A);

// iteration:
for (List<String> x : Arrays.asList(A, B, C)) {
    // do something to x.get(0), analogous to x[0] in Python    
}

(见Arrays.asList()

于 2013-08-16T20:12:35.500 回答
0

列表将满足您的目的。

            String[] A ={"a","bnbnb"};
            String[] B = {"1","2","3"};
            List<String> C = new ArrayList<String>();

            C.add("X");
            Collections.addAll(C,A);

            System.out.print(C); 
于 2013-08-16T20:14:05.107 回答