10

Can someone please explain what the difference between ArrayList<?>, ArrayList and ArrayList<Object> is, and when to use each? Are they all same or does each have some different meaning at the implementation level?

5
  • 7
    Time to read about Java Generics Commented Aug 29, 2013 at 14:14
  • I generally don't put any parameters... its "fake" generic anyway. Commented Aug 29, 2013 at 15:24
  • 3
    @texasbruce That's really a bad idea. Commented Aug 29, 2013 at 16:11
  • @arshajii sometimes you have to. Like a HashMap to be dumped as a JSON, the value may be string, number, or array, etc. You cant specify the generic as HashMap<String, XXX>, or just has to be Object. Commented Aug 29, 2013 at 16:14
  • 1
    @texasbruce It would be preferable to use Object. Bad things can happen when you use raw types. Commented Aug 29, 2013 at 16:15

2 Answers 2

19

ArrayList<Object> is specifically a list of Objects whereas ArrayList<?> is a list whose concrete type we are unsure of (meaning we can't add anything to the list except null). You would use the latter when the list's type is irrelevant, e.g. when the operation you want to perform does not depend on the type of the list. For instance:

public static boolean isBigEnough(ArrayList<?> list) {
    return list.size() > 42;
}

This is all covered in the generics tutorial (see the wildcards section).

Finally, ArrayList with no type parameter is the raw type: the only reason it's even allowed is for backwards compatibility with Java versions under 5, and you should refrain from using it whenever possible.

Sign up to request clarification or add additional context in comments.

2 Comments

this is a new perspective :)
Very nice. I was using ArrayList in some test projects (as I saw it used in a few tutorials.) The takeaway is, Always use <Object> when you can
1

ArrayList<?> means "an ArrayList instance containing a type which is to be determined"

ArrayList is the class of an ArrayList

An ArrayList<Object> means an instance of ArrayList containing Object types.

This looks like it could be a good write-up on this (and more): http://docs.oracle.com/javase/tutorial/java/generics/types.html

1 Comment

I guess the OP is asking that since in JAVA everything extends from Object, what does it mean to have "a type which is to be determined"? Because the list does not accept primitives

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.