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...

kingified
  • 195
  • 1
  • 2
  • 18

2 Answers2

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.

Aivean
  • 10,692
  • 25
  • 39
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#"));
...
jcurley
  • 66
  • 5
  • Thanks for the response. Does that mean I can't use ArrayList again as method parameter. is there a way out with ArrayList? – kingified Oct 29 '21 at 21:28
  • 1
    @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. – David Conrad Oct 29 '21 at 21:49
  • Thanks for the insight – kingified Oct 29 '21 at 23:54