Mushfiq Mammadov wrote:I couldn't find any difference and I want to know what is the difference between line1 and line2 in the following code?
Before Java 5 generics didn't exist at all. So you created an ArrayList as follows
This code has several issues:
you can add anything to list (strings, integers, cats, dogs,...), so no type checking by the compilerif you get an element of list, its type is always Object. Even if it was guaranteed to be a list with only strings, list.get(0) would return an Object (the actual object is of course a String). So if you wanted to invoke the length method, you had to cast to String first (and you know casting could be dangerous)
Some code to illustrate the above
As you can see, it was a lot harder to make sure a list contained only strings. And even if it was such a list, you had to write some lines of code to treat the elements as strings instead of objects. Therefore adding generics to Java was a huge improvement! Code becomes smaller, easier to read and you get type checking at compile time.
That was a little history lesson! Now back to your original question. If you write
the list will work exactly the same as when you would have used
ArrayList<String> list5 = new ArrayList<String>(); or
ArrayList<String> list5 = new ArrayList<>();. But the compiler will produce a warning because you are mixing generic with non-generic code. Because the type of the reference variable is
ArrayList<String>, you'll get the type checking at compile time.
If you do it the other way round (
ArrayList list5 = new ArrayList<String>(); or
ArrayList list5 = new ArrayList<>();), the code will still compile (with the same warning about mixing generic with non-generic code). But now
list5 can hold any object (strings, integers, cats, dogs,...), because type of the reference variable is
ArrayList and thus no type checking occurs at compile time (as in pre Java 5 code).
Hope it helps!
Kind regards,
Roel
(Disclaimer: for the
OCAJP exams you don't have to worry about combining generic with non-generic code, it's not on these exams. But for the OCPJP exam you have to know all little intricacies about combining generic with non-generic code)