how to get elements of a list in java

www.laut‮rut‬i.com
how to get elements of a list in java

To get elements of a list in Java, you can use the get() method of the List interface. This method takes an index as an argument and returns the element at the specified index in the list.

Here's an example of how you can get elements of a list in Java:

import java.util.List;

// ...

List<String> names = List.of("Alice", "Bob", "Charlie", "David");

String firstName = names.get(0);
String secondName = names.get(1);
String thirdName = names.get(2);
String fourthName = names.get(3);

In this example, the names list is a List object containing four strings. The firstName, secondName, thirdName, and fourthName variables hold the elements at the respective indices in the list.

It's important to note that the get() method throws an IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()). You should ensure that the index is within the bounds of the list before calling the get() method.

Created Time:2017-11-01 20:42:54  Author:lautturi