We create a Set
as:
Set myset = new HashSet()
How do we create 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 .
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.
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");
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With