Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

package vs. specific imports

 
Junilu Lacar
Bartender
Pie
Posts: 7758
61
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic