0

In Python I can do some simple stuff like:

# 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]

And so on.

I am new to Java - and understand that arrays are fixed size, but lists and array lists arent. How would I mimic the above?

Here is my failed attempt

# 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]

Using ArrayLists just kept making it more cumbersome - bet I am missing something obvious.

2 Answers 2

2

You should use Lists instead:

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    
}

(See Arrays.asList())

Sign up to request clarification or add additional context in comments.

2 Comments

Got it - The example on the link makes this clear - List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
And for [A,B,C] is the equivalent List<List<String>> D = Arrays.asList(A,B,C) ?
0

List would serve your purpose.

            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); 

1 Comment

This isn't equivalent to the Python code. C should be a list of strings containing ["x","a","bnbnb"].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.