How to make a new List in Java
In Java, you can create a new list using the java.util.ArrayList
class or the java.util.LinkedList
class.
Here's an example of how to create a new ArrayList:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create a new ArrayList of Strings
ArrayList<String> names = new ArrayList<>();
// Add some elements to the list
names.add("Alice");
names.add("Bob");
names.add("Charlie");
}
}
To create a new LinkedList
, you can use the following code:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// Create a new LinkedList of Strings
LinkedList<String> names = new LinkedList<>();
// Add some elements to the list
names.add("Alice");
names.add("Bob");
names.add("Charlie");
}
}
Both ArrayList and LinkedList
are implemented as generic classes, so you can specify the type of elements that the list will hold by using type parameters. In the examples above, we used ArrayList<String>
and LinkedList<String>
to create lists of strings. You can use any valid Java type as the type parameter, for example ArrayList<Integer>
for a list of integers or LinkedList<MyClass>
for a list of objects of a custom class.
Note that both ArrayList and LinkedList
are part of the java.util
package, so you need to import one of these classes in your code to use it.