We create a Set
as
Set myset = new HashSet()
How do we create a List
in Java?
We create a Set
as
Set myset = new HashSet()
How do we create a List
in Java?
One example:
List somelist = new ArrayList();
You can look at the javadoc for List and find all known implementing classes of the List
interface that are included with the java api.
List myList = new ArrayList();
or with generics
List<MyType> myList = new ArrayList<MyType>();
First read this, then read this and this. 9 times out of 10 you'll use one of those two implementations.
In fact, just read Sun's Guide to the Collections framework.
Additionally, if you want to create a list that has things in it:
List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
//simple example creating a list form a string array
String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};
List mylist = Arrays.asList(myStrings );
//getting an iterator object to browse list items
Iterator itr= mylist.iterator();
System.out.println("Displaying List Elements,");
while(itr.hasNext())
System.out.println(itr.next());
Sometimes - but only very rarely - instead of a new ArrayList, you may want a new LinkedList. Start out with ArrayList and if you have performance problems and evidence that the list is the problem, and a lot of adding and deleting to that list - then - not before - switch to a LinkedList and see if things improve. But in the main, stick with ArrayList and all will be fine.
List is just an interface just as Set.
Like HashSet is an implementation of a Set which has certain properties in regards to add / lookup / remove performance, ArrayList is the bare implementation of a List.
If you have a look at the documentation for the respective interfaces you will find "All Known Implementing Classes" and you can decide which one is more suitable for your needs.
Chances are that it's ArrayList.
There are many ways to create a Set and a List. HashSet and ArrayList are just two examples. It is also fairly common to use generics with collections these days. I suggest you have a look at what they are
This is a good introduction for java's builtin collections. http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html
Using Google Collections, you could use the following methods in the Lists class
import com.google.common.collect.Lists;
// ...
List<String> strings = Lists.newArrayList();
List<Integer> integers = Lists.newLinkedList();
There are overloads for varargs initialization and initialising from an Iterable<T>
.
The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor - the compiler will infer it from the type of the variable.