*
The moose likes Java in General and the fly likes Java Collections 2 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Collections 2" Watch "Java Collections 2" New topic
Author

Java Collections 2

Aruna Balasuriya
Ranch Hand

Joined: Nov 14, 2009
Posts: 44
what is the difference between

List<String> x = new ArrayList<String>();

and

List<String> x = new ArrayList();
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Aruna Balasuriya wrote:what is the difference between

List<String> x = new ArrayList<String>();

and

List<String> x = new ArrayList();


The difference is formal only but you probably will get a warning from the compiler that the ArrayList is of a raw type and should be parametrized. The type safety of the x variable isn't compromized by this.

In fact in Java 7 the second declaration will become accepted and the norm I guess. It's because the compiler can easily infer the type of the ArrayList from the type of the variable and this saves a lot of unnecessary typing.

Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Embla Tingeling wrote:In fact in Java 7 the second declaration will become accepted and the norm I guess. It's because the compiler can easily infer the type of the ArrayList from the type of the variable and this saves a lot of unnecessary typing.

I believe the second declaration above will still be incorrect under JDK 7. The new syntax is slightly different, requiring a minimal "<>":

Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Mike Simmons wrote:
List<String> x = new ArrayList<>();


Possible, but it really isn't necessary. We'll have to wait and see.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Well, the <> syntax is definitely what's specified in the original proposal. The possibility of omitting it is discussed:
...it could be argued thatinference would look cleaner without the <> token:

Map<String, List><String>> list = new Map();

Unfortunately, for the purposes of backwards compatibility, new Map() indicates a raw type, and therefore cannot be used for type inference.

I agree that they could change this, but so far I've seen no indication that they will. Sun has generally treated backwards compatibility as a sacred cow - even pointless backward compatibility such as this. The Project Coin developers may now come from many companies besides Sun, but so far it looks like they're sticking with Sun's traditional attitudes towards backwards compatibility, for better or worse.
 
GeeCON Prague 2014
 
subject: Java Collections 2