Creating a new ArrayList in Java
Solution 1
You are looking for Java generics
List<MyClass> list = new ArrayList<MyClass>();
Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html
Solution 2
If you just want a list:
ArrayList<Class> myList = new ArrayList<Class>();
If you want an arraylist of a certain length (in this case size 10):
List<Class> myList = new ArrayList<Class>(10);
If you want to program against the interfaces (better for abstractions reasons):
List<Class> myList = new ArrayList<Class>();
Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.
Solution 3
You're very close. Use same type on both sides, and include ()
.
ArrayList<Class> myArray = new ArrayList<Class>();
Solution 4
You can use in Java 8
List<Class> myArray= new ArrayList<>();
Solution 5
Fixed the code for you:
ArrayList<Class> myArray= new ArrayList<Class>();
Unknown user
Updated on July 09, 2022Comments
-
Unknown user almost 2 years
Assuming that I have a class named
Class
,And I would like to make a new ArrayList that it's values will be of type
Class
.My question is that: How do I do that?
I can't understand from Java Api.
I tried this:
ArrayList<Class> myArray= new ArrayList ArrayList<Class>;
-
AlexR about 13 yearsNever use this! It is extremely bad practice to use concrete class at the left side of assignment when interface is available.
-
Mr. Lance E Sloan over 11 yearsThat link to a tutorial PDF from Sun is broken. This series of web pages from Oracle should be helpful: docs.oracle.com/javase/tutorial/java/generics/index.html
-
Noumenon about 11 yearsNot sure what's wrong, this looks like all the other answers. They must have edited?
-
Kyle Clegg almost 11 yearsI often see just "List" on the left side (like in the accepted answer). Why do you suggest ArrayList on both sides?
-
Zakaria over 10 years@KyleClegg mellamokb just took the code line from the question. If your question was about "List vs ArrayList", you can find some answers here : stackoverflow.com/questions/2279030/…
-
Zakaria over 10 years@AlexR Nothing can prevent you from using the ArrayList class on the left type if you want to use ArrayList's specific methods (trimToSize, removeRange, ...) as the List interface doesn't contain these methods.
-
Erik Humphrey over 6 yearsCan also be shortened to
List<MyClass> list = new ArrayList<>();
, at least in Java 8. -
Pontios about 4 yearsWhat is the advantage of not writing Class in the <> of the right handside ?