Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass List in my method parameter?

Can someone explain how to define a List parameter such that i can pass a List to it. My method looks something like this. I need LIST to be replaced so the method recognizes "listname" as a list.

public static void function(int number, LIST listname) {
  for (int i = 0; i < listname.size(); ++i {
    System.out.print(listname.get(i) + ": ");
  }
  System.out.println(number);
}

In my main method I will call on the method as such:

List<String> myList = new ArrayList<String>();
  myList.add("item1");
  myList.add("item2");
  myList.add("item3");

function(4, myList);
like image 897
Jonathan Mousley Avatar asked Jul 16 '16 23:07

Jonathan Mousley


People also ask

How do you pass list elements as parameters in Python?

In Python, we can easily expand the list, tuple, dictionary as well as we can pass each element to the function as arguments by the addition of * to list or tuple and ** to dictionary while calling function.

How do you pass parameters to a method?

Parameters and Arguments Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

Can you pass a list to a function in Python?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.


2 Answers

Change the method definition to something as follows

public static void function(int number, List<String> listname) {
  for (int i = 0; i < listname.size(); ++i) {
    System.out.print(listname.get(i) + ": ");
  }
  System.out.println(number);
}
like image 120
user2420211 Avatar answered Oct 02 '22 09:10

user2420211


The Type should be a List<String> there is no standard LIST Type in Java (unless you make it ofcourse).

like image 34
Gherbi Hicham Avatar answered Oct 02 '22 08:10

Gherbi Hicham