What is the proper style for listing imports in Java?

前端 未结 10 1035
梦谈多话
梦谈多话 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条回答
  •  -上瘾入骨i
    2021-02-18 16:21

    Use import individually.

    It is way lot better for production code to list each and every one of the classes being imported.

    While the IDE's do a great job helping you know which classes are being used, it is more readable to know that you're referring to :

    java.util.List;
    

    and not

    java.awt.List; 
    

    and so on.

    Additionally it is recommended that you group them by package starting by the core libraries passing by 3rd party and ending with own project libraries:

     import java.util.List;
     import java.util.ArrayList;
     import java.util.Date;
    
     import javax.swing.JFrame;
     import javax.swing.JPanel;
    
     import javax.swing.event.TableModelListener;
    
     import org.apache.commons.httpclient.cookie.CookiePolicy;
     import org.apache.commons.httpclient.cookie.CookieSpec;
    
     import your.own.packagename.here.SomeClass;
     import your.own.packagename.here.OtherClass;
    

    Using wildcard is acceptable for small self project/classes. It is faster, but it is not expected to be maintainable. If any other developer is involved, use the first.

提交回复
热议问题