What is the proper style for listing imports in Java?

前端 未结 10 1064
梦谈多话
梦谈多话 2021-02-18 16:01

Is it better to list each individual piece of a package you\'re going to need (see #1) or is it better to just import everything from a package (see #2)?

1



        
相关标签:
10条回答
  • 2021-02-18 16:23

    There is no one right answer here.

    The People Who Brought You Eclipse voted for individual imports, since Source/Organize Imports will convert the * form to the specific form.

    0 讨论(0)
  • 2021-02-18 16:27

    If you list them individually it is easier to detect, when reading code with a simple editor (rather than from inside a dev environment), which package objects come from. When reading code from complex projects this can save significant time. Had an example of that earlier today, in fact, when I was studying code from a large open source project without wanting to load everything into eclipse.

    0 讨论(0)
  • 2021-02-18 16:28

    It's NOT simply a matter of style; import-on-demand can result in code that ceases to compile as new classes are added to existing packages.

    Basic idea (See http://javadude.com/articles/importondemandisevil.html for details.):

    import java.awt.*;
    import java.util.*;
    ...
    List list;
    

    worked in Java 1.1; as of Java 1.2, the above code will no longer compile.

    Import on demand is EVIL because your program can stop compiling when new classes are added to existing packages!

    ALWAYS use explicit imports. It's not a matter of style; it's a matter of safety.

    This is especially bad if you check in perfectly-compiling code and a year later someone checks it out and tries to compile it with new class libraries.

    (Import-on-demand is an example of a really bad programming language feature - no feature should break code when new types are added to a system!)

    0 讨论(0)
  • 2021-02-18 16:29

    Import individually, it saves the compiler from having to look through each package for each class and therefore makes things run quicker.

    0 讨论(0)
提交回复
热议问题