The moose likes Java in General and the fly likes package vs. specific imports Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "package vs. specific imports" Watch "package vs. specific imports" New topic

package vs. specific imports

Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

I seem to recall reading somewhere (I think it was Craig Larman's book "Java 2 Performance and Idioms") that you should use package imports over specific imports:
// specific
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
// import whole package is better
import java.util.*;

I don't remember the reasons so if somebody has any idea, I'd appreciate a short summary. Thanks!

Junilu - [How to Ask Questions] [How to Answer Questions]
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

There is really no difference code-wise!!!

The only case where package vs. specific imports matter at all is in the case of name collisions... For example, java.util.Date and java.sql.Date. If you do package imports on both of those, the compiler won't know which you are talking about if you create a Date object! If you really aren't using both Date classes there are several ways to work around this...

  • Do specific imports for only the classes you need...
  • Do package imports for the package you aren't using the Date class from... then, do a specific import on the Date class you are using... the compiler will figure it out...

  • If you really are using both classes in a name collision, there is no way around it... you'll have to specify the complete package and class name every time you refer to the classes in question... i.e. java.sql.Date and java.util.Date...

    At the company I work at using specific imports is enforced by the coding standards. This is done so a programmer can see exactly what classes their class depends on, so if something breaks, you don't have to check into all the classes that changed recently... only the ones specificly imported.


Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I agree. Here's the link:
subject: package vs. specific imports
It's not a secret anymore!