WaveRunner
WaveRunner

Reputation: 67

In Java, what is the advantage of declaring and initializing a java.util.(ex. list) in the body of the class as opposed to just importing is first?

For example,

public final static java.util.List VALUES = 
  Collections.unmodifiableList( 
    Arrays.asList( new Suit[] { CLUBS, DIAMONDS, HEARTS, SPADES } ) );

confused me in the way that it was written. I'm so used to seeing java.util being imported.

Thanks for the help.

Upvotes: 2

Views: 103

Answers (3)

Dave
Dave

Reputation: 6179

There isn't a difference. There might be a "best practice" somewhere which states that you should import as opposed to giving fully namespaced classes where possible (or maybe the other way around).

Using the full namespace as opposed to just doing an import becomes useful when you start using 3rd party libraries together. Say, for example you had a library to parse a csv and another to build an xml (building csv to xml). Both libraries might declare a class called "Parser". If you import them both, the compiler won't be able to tell which "Parser" class you're referring to, so that is a situation where you would want to use the full namespace as opposed to simply importing.

Upvotes: 0

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181290

Your code will be more readable if you do the import, specially when you are using multiple times the same class.

I think this is more readable:

import java.util.List;

class A {
    List l1;
    List l2;
}

Than this:

class A {
    java.util.List l1;
    java.util.List l2;
}

Things will get even more clean when you start using generics on some declarations.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500775

There's no benefit in doing that unless you've got another List class which is already being imported. Perhaps that's the case here?

Upvotes: 6

Related Questions