-5

I want to make a method that takes x amount of ArrayList<> as a parameter. When I use args this does not work. Is args only reserved for int and String etc? Why does not args become a new array containing my arraylist? I thought there was a way to be able to give multiple parameter values to a method that turns into an array inside the method?

ArrayList<String> list1 = new ArraytList();
list1.add("1");
ArrayList<String> list2 = new ArrayList();
list2.add("2");
list2.add("3");

A print method:

public void print(ArrayList<String> args){
    for(int i = 0; i < args.length; i++){
        for(int j = 0; j < args[i].size(); j ++){
            System.out.println(args[i].get(j));
        }
    }
}

Does not work

Lealo
  • 331
  • 1
  • 3
  • 11
  • 5
    That's because you're trying to pass two arraylists into your method when it will only accept one. – Joe C Apr 05 '17 at 20:58
  • 1
    Yeah, your printElements takes only one parameter but you are passing two. – steve Apr 05 '17 at 21:00
  • Also, I am assuming you're using lambda expression to make your code shorter and more concise? in that case you can reduce your lambda expression to this -----> args.forEach(System.out::println); – Ousmane D. Apr 05 '17 at 21:10
  • When you use lambda and foreach like that - and want to change something to all the elemnts, that variable or whatever it is has to be declared outside the method, which I think usally becomes more messy. So I usally stick with for loops at all times. But yes that would have maken it this shorter. – Lealo Aug 16 '17 at 01:51

2 Answers2

2

printElements takes a single parameter of type ArrayList<String>, but you're trying to give it two arguments of type ArrayList.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • If I would do `printElements(String args)`, that would take more than one String as paramater - and args is an array. I would like to have a parameter taking in x amount of arrays and turn them into a nested array (args) - just the same way. – Lealo Apr 05 '17 at 23:29
  • @Lealo no. That would take a single array as a parameter. If you want to take any number of `ArrayList` parameters, then set the type of ages to `ArrayList...` or ArrayList>` – Alexander Apr 06 '17 at 01:08
  • The `ArrayList ... args` was what I was looking for! – Lealo Apr 06 '17 at 01:22
0

Use

first.addAll(second);
printElements(first);
xlm
  • 6,854
  • 14
  • 53
  • 55
stinepike
  • 54,068
  • 14
  • 92
  • 112