0

I have a method that takes in a nested ArrayList of Strings as a parameter as given below:

 public static String methodName(ArrayList<ArrayList<String>> param1,ArrayList<Integer> param2){
...some logic
}

I want to test this method with an input

input :"param1"= [
    ["HTML", "C#"],
    ["C#", "Python"],
    ["Python", "HTML"]
  ]
  "param2"= [0, 0, 1]

I searched online and found this : How do I declare a 2D String arraylist?

Here is what I tried:

public static void main(String[] args){
ArrayList<ArrayList<String>> param1 = ...what should I put here?    

  List<List<String>> list = new ArrayList<List<String>>();
   List<String> input = new ArrayList<String>();
   input.add({"HTML", "C#"});//does not compile ... array initializer not allowed here
  input.add({"C#", "Python"});
  input.add({"Python", "HTML"});

How would you add the input to the nested ArrayList? Would appreciate any help...

2 Answers 2

2

Since param1 is declared as ArrayList<ArrayList<...>>, you have no choice, but to create new ArrayList(...) explicitly for nested elements:

ArrayList<ArrayList<String>> param1 = new ArrayList<>(Arrays.asList(
    new ArrayList<>(Arrays.asList("HTML", "C#")),
    new ArrayList<>(Arrays.asList("C#", "Python"))
));

But, as the general rule, try to write functions that accept as permissive parameter types as possible. In this case, if you can replace ArrayList<ArrayList<String>> in methodName with List<List<String>>, that would be much better for the users of your function.

For example, they would be able to create param1 as such:

List<List<String>> param1 = Arrays.asList(
    Arrays.asList("HTML", "C#"),
    Arrays.asList("C#", "Python")
);

UPD as @DavidConrad pointed out, you can use List.of(...) instead of Arrays.asList(...) since Java 9.

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

2 Comments

Thanks for this... both solutions worked. I needed the ArrayList option for local testing. Appreciate your insights.
Or using List.of instead of Arrays.asList
1

You could do

List<List<String>> list = new ArrayList<>(); // No need for List<String> again, just the one diamond operator is enough here.
list.add(List.of("HTML", "C#"));
...

3 Comments

Thanks for the response. Does that mean I can't use ArrayList again as method parameter. is there a way out with ArrayList?
@kingified You could wrap the List.of calls like new ArrayList<>(List.of("HTML", "C#")) and use ArrayList in the declaration instead of List, but programming against the interface rather than the implementation is good advice, and pretty standard in Java.
Thanks for the insight

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.