jQuery in Action, 2nd edition*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "package vs. specific imports" Watch "package vs. specific imports" New topic
Author

package vs. specific imports

Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4419
    
    5

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
Bartender

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.

    -Nate


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: package vs. specific imports
 
Similar Threads
about import statement
importing from same name packages
What is the disadvantage of using "*" in an import statement??
difference between package and import
Importing Classes