In an ArrayList for android such as the simplelistadapter I commonly see ArrayList<?> and in some tutorials I've reviewed the <?> is replaced by some value. But I'm still not quite sure what variable or qualifier this stands for.
6 Answers
It's called Generics.
For example, you can do this:
ArrayList<Integer> list = new ArrayList(); list.add(new Integer(1)); list.add(new Integer(2)); ..... Integer i = (Integer)list.get(1); Or you can do:
ArrayList<Integer> list = new ArrayList<Integer>(); list.add(new Integer(1)); list.add(new Integer(2)); ..... Integer i = list.get(1); As you can see, no need for casting.
4 Comments
The is a wildcard character for a generic type. Normally you declare an array list like:
ArrayList<String> Where the type is specified exactly. The list will contain Strings. But sometimes you want to make a method or a class that takes an ArrayList of any type, or you want a field that points an ArrayList of any type
public void removeFirstItem(ArrayList<?> target) { ... } Now this method can take an ArrayList<String>, or an ArrayList<Long>, etc, and do some operation on it.
Similiary you can have a local variable:
ArrayList<?> someList; someList = new ArrayList<String>(); someList = new ArrayList<Long>); This works, whereas:
ArrayList<String> someList = new ArrayList<String>(); someList = new ArrayList<Long>(); Will not, since someList is specified as an ArrayList<String>, so only ArrayList<String> can be assigned to it.
Comments
Similar to ArrayList<? extends Object>, which means it can contain any object inherits from Object class (i.e. All objects in Java).
3 Comments
ArrayList<int>, you can only make an ArrayList<Integer>, because an int is a primitive type and can't be null, but an Integer is a real Java type and can, in fact, be null.The syntax is a "wildcard". It's needed with Java generics:
A wildcard can be "bounded" or "unbounded". The whole issue of compile/design time generic typing is closely associated with the runtime JVM issue of "type erasure":
http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html
http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
'Hope that helps .. pSM
Comments
This is a question regarding generics. The <(Kind of Object)> syntax represents that only a certain kind of object (class instance) may be passed as an argument. When you have the syntax, you are saying that any kind of class instance may be passed.
ArrayList<?>, it could contain aLong, aString, and even aMap. AnArrayList<Integer>, however, could only containIntegervalues.