2

i hope my question won't sound stupid but i'd like to know what's the difference between these two lines:

(Assuming I made a class named Cow..)

ArrayList<Cow> c1 = new ArrayList<Cow>();

ArrayList<Cow> c2 = new ArrayList();

Thanks in advance for ur explanation.

3
  • Try compiling the code with the javac -Xlint option and see what the compiler has to say about it. Commented Feb 29, 2012 at 15:10
  • You will get these annoying warnings in eclipse (for example) if you use the second option : ) Commented Feb 29, 2012 at 15:12
  • Ye something came up, even by using javac without the 2nd attribute u just gave it notes something, well anyway i dont care much about the tech details i just like to know if the list itself is different in some way.. Commented Feb 29, 2012 at 15:15

2 Answers 2

7

Currently, there is essentially no difference, due to type erasure. The first form is preferred; the second form uses a raw type, and is only supported for backward-compatibility with older versions of Java. A good compiler will give you warnings if you use it.

As the Java Language Specification, Third Edition, §4.8 explains:

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

(emphasis in original).

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

1 Comment

hm got it! so as u said the list itself is basiclly the same, well explained mate :)
1

As ruakh has just pointed out, the first one is preferred, and actually there won't be any difference duriong execution.

Explained in simpler words: In both lines you are declaring a list of Cow In the first line you instantiate it with a list of Cow. In the second one you instantiate it with a list of Object (and Cow is a subclass of Object).

It would be even better to declare it as the list interface List.

List<Cow> listOfCows = new ArrayList<Cow>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.