Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a new List in Java

We create a Set as:

Set myset = new HashSet() 

How do we create a List in Java?

like image 611
user93796 Avatar asked May 13 '09 15:05

user93796


People also ask

How do you add to a list in Java?

There are two methods to add elements to the list. add(E e ) : appends the element at the end of the list. Since List supports Generics , the type of elements that can be added is determined when the list is created. add(int index , E element ) : inserts the element at the given index .

How do I create a list from one list to another in Java?

Way #1. Create a List by passing another list as a constructor argument. List<String> copyOflist = new ArrayList<>(list); Create a List and use addAll method to add all the elements of the source list.


2 Answers

Additionally, if you want to create a list that has things in it (though it will be fixed size):

List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You"); 
like image 26
Aaron Maenpaa Avatar answered Sep 20 '22 07:09

Aaron Maenpaa


List myList = new ArrayList(); 

or with generics (Java 7 or later)

List<MyType> myList = new ArrayList<>(); 

or with generics (Old java versions)

List<MyType> myList = new ArrayList<MyType>(); 
like image 142
Dan Vinton Avatar answered Sep 20 '22 07:09

Dan Vinton