To return a list in Java, you can use the return
statement in a method. The return
statement causes the method to exit and provides a value back to the calling code.
Java provides several classes in the java.util
package that implement the List
interface, such as ArrayList
and LinkedList
. You can use any of these classes to create a list and return it from a method.
Here is an example of how you can return a list in Java:
import java.util.ArrayList; import java.util.List; class Main { public static void main(String[] args) { List<String> names = getNames(); for (String name : names) { System.out.println(name); } } public static List<String> getNames() { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); return names; } }
In this example, the getNames
method returns a list of strings with the values "Alice", "Bob", and "Charlie". The returned list is then assigned to the names
variable in the main
method, and its values are printed to the console using a for-each
loop.
Note that the type of the list being returned must be specified in the method signature. In this case, the getNames
method returns a list of strings, so the method is declared as public static List<String> getNames()
.