Advertisement
Advertisement


Creating a new ArrayList in Java


Question

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>;
2011/05/06
1
41
5/6/2011 7:05:50 PM

Accepted Answer

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

2013/12/13
57
12/13/2013 2:37:49 PM

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.

2013/06/10

You're very close. Use same type on both sides, and include ().

ArrayList<Class> myArray = new ArrayList<Class>();
2011/05/06

You can use in Java 8

List<Class> myArray= new ArrayList<>();
2016/06/29

Do this: List<Class> myArray= new ArrayList<Class>();

2013/02/14

Fixed the code for you:

ArrayList<Class> myArray= new ArrayList<Class>();
2011/05/06

Source: https://stackoverflow.com/questions/5915892
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]