This question already has answers here:
Java import all from all
(3 answers)
Closed 9 years ago.
Why doesn't import one.two.* include import one.two.three.MyClass?
Shouldn't Java have something like import one.two.**? Or is there any reason (other than they just didn't do, not that they couldn't do it)?
Thanks
Java does not treat packages as truly subclassing each other; while java.util and java.util.concurrency might look like the second is somehow part of the first, they are treated as entirely independent and the dot is mostly there for neatness.
This means you don't need to be afraid of naming your class or interface the same as another one declared in some super- or sub-package on a later date, and it also means you should really just write a couple extra lines of imports.
The reasons behind this decision, as Peter Lawrey explained, stem from Java's general lean towards simplicity. Best practice is often to never use import wildcards at all anyway.
Java treats each package as independent. For example, package local don't extend to any "sub" packages. I suspect using the hierarchy in a meaningful way would be valuable but Java's design was to make everything as simple as possible.
Or is there any reason (other than they just didn't do, not that they couldn't do it)?
The problem is backward compatibility which might break older programs. I suspect this is solvable.
In truth, most IDEs manage your imports for you and I don't even look at my imports any more. Certainly avoiding import * is preferable so that all classes are explicitly imported.
Related
This question already has answers here:
Why is using a wild card with a Java import statement bad?
(18 answers)
Closed 8 years ago.
Is using
import java.util.*
not favorable compared to calling on the specific packages? I was wondering if its significantly inefficient to a program to call on all the packages, rather than listing them out specifically such as:
import java.util.Scanner;
import java.util.Math;
etc. I am preparing for interviews and want to make sure I have good coding practices.
The problem with importing * is that it increases the chance of naming conflicts.
Let's assume that in your program, you have a class called EventListener, since java.util also has a class called EventListener, right the way you have some conflicts to deal with, but you do not even care that java.util.EventListener in this context.
This really can be avoided, simply by not importing * and only importing specific classes that are truly needed.
#PeterPeiGuo is right, besides that, I want to say I don't use import xxx.xx.*, cause as a developer you need to know which class you should use and which class not. You need to understand everything for your code/application. So import xxx.xx.XXX is better from my view.
arraylists, buffered reader, scanner, etc.. all "Default" classes that "already exist" in the language..
unlike, say, public class widthOfTable which would be a "made up" class , that " did not already exist in language"..
why is there no term to distinguish these ideas when teaching? I barely discovered this difference in college , despite being here 3 years.
Actually, there is a pretty strong distinction between what you called "default" and "made-up" classes, which has to do with their package names.
All "default" classes are in some java.* package (java.lang, java.util, etc.), and no "made up" class could use a package name that starts with java..
As for the fact that this distinction is blurred "when teaching", my feeling is that it's intentional. Java as a language is pretty much a set of keywords and syntax rules plus a java.lang.Object class that nobody could avoid extending (and which uses a few other built-in types like String, Integer and some exceptions).
The JDK is a Java library to help you with the most common use-cases, but in some cases there are better alternatives.
In my opinion, it would be a mistake to teach someone that java.util.Calendar or the java.util.logging stuff have any advantage over JodaTime or SLF4J just because they're in the classpath by default.
I had the same question in my mind before and i had a different term for your word default and I called them built-in classes.
why is there no term to distinguish these ideas when teaching?
there is already but taught indirectly using the terms packages and namespaces
if there is a time that you will design a programminng language you can tell any developer what are those default or built classes by putting them in right packages and namespaces for example
mydefaultclasses.io.print
mydefaultclasses.io.read
in java its really understandable that any classes under java namespace is a default or built-in class. it really depends upon what will came up on the documentation of the language you are trying to learn.
Not sue if I totally understand your question, but you can find all the predefined classes in Java under the Java Class Library: Java Class Library.
Actually it is more powerful to have packages or namespaces. Your way of thinking is like an implementation that only supports two namespaces. The standard library (in this case the java.*, in c++ std) is one, the other is all your other stuff. After a while, you probably end up with a new set of "default" classes anyway and you put those in a package to avoid clutter your global namespace.
What is effected by redundant java import statements?
Do they effect the compiled runtime (performance/size)?
or just stuff like intellisense?
To ask differently:
how important is it to remove them?
Import statements only affect what happens during compile time.
The compiler takes this code, and creates a .class file that represents your code in an executable format (something in binary).
In the end, the binaries are exactly the same, but the method by which they are made are different.
Let's look at a simple case:
import java.util.*;
vs
import java.util.ArrayList;
import java.util.List;
when used in:
//...
List <String> someList = new ArrayList <String> ();
//...
When the compiler hits the word List, in the first case, it will need to figure out if List exists in that set of classes or not. In the second case, it is already given it explicitly, so its much easier.
In essence, what happens is the compiler must take all the classes existing in the import statements and keep track of their names so that, if you use it, the compiler can then retrieve the appropriate functions that you are calling.
Sometimes, there are classes that have the same name in multiple packages. It is in this case (which Thomas is referring to) that you should not use the * to select all the classes in the directory.
It is best practice to explicitly describe your class usage.
It doesn't impact performance to have excess import statements. It may make the source code longer than it should be but there is no effect on the compiled code. Java itself imports unnecessary class files - see the Java Language Specification section 7.5.5:
Each compilation unit automatically imports all of the public type
names declared in the predefined package java.lang, as if the
declaration:
import java.lang.*;
appeared at the beginning of each
compilation unit, immediately following any package statement.
Section 7.5.2 says that
A type-import-on-demand declaration never causes any other declaration
to be shadowed.
...meaning that wildcard imports won't trump single-entry imports.
As others have pointed out, any decent IDE (NetBeans, Eclipse, etc) will remove unused imports for you.
Like many questions about performance, clarity of the code is usually more important. This should be your first thought, and only in the rare cases where you have a known (measured) performance problem you should consider not writing the simplest and clearest code you can.
Like many performance questions, in this case the simplest, clearest code is also the fastest.
You should maintain your import or have your IDE maintain them, to keep them clear and make you code easier to maintain. The performance issue is very small, even for the compiler or IDE.
The biggest danger is namespace collisions. If two imported libraries both have a List type for example, it may not use the one you think it is.
It is important to remove them because they add bloat to the .java file and because getting rid of them within a given file is fast and cheap, especially if you're using an IDE (CTRL-SHIFT-O, I believe, is the shortcut in Eclipse).
As far as "What do redundant imports do for the machine", well, not much really. The class itself will only be added to the relevant jar file once, and it will only be loaded once per class (please see not vis-a-vis "per class"), so aside from adding some trivial amount of time to compilation, it won't really have any substantial long-term effect on the program itself.
That said, it is cheap and easy to fix the problem: if you aren't using an IDE, then you should have clearly grouped import statements which are in some sane order to begin with (I alphabetize mine, meaning that I'll immediately see two imports of java.util.Map, because they'd be right next to each other!). Your fellow coders will actively complian if you don't fix it, so I suggest that it is in your best interest to do so.
Why does Eclipse take a fine grained approach when importing types? In C# I'm used to things like "using System.Windows.Controls" and being done with it, but Eclipse prefers to import each widget I reference individually (using the Ctrl+Shift+O shortcut). Is there any harm to importing an entire namespace if I know I'll need multiple types in it?
Eclipse has a great setting called the "Organize Imports" in the Window -> Preferences dialog that lets you say when N classes are used from a package, do a wildcard import. I use it at N=2 or 3 usually.
Somebody can read your code without IDE - in this case non-wildcard imports will help him to figure out which classes are used in your code.
The only harm that wildcard package imports can cause is an increased chance of namespace collisions if there are multiple classes of the same name in multiple packages.
Say for example, I want to program to use the ArrayList class of the Java Collections Framework in an AWT application that uses a List GUI component to display information. For the sake of an example, let's suppose we have the following:
// 'ArrayList' from java.util
ArrayList<String> strings = new ArrayList<String>();
// ...
// 'List' from java.awt
List listComponent = new List()
Now, in order to use the above, there would have to be an import for those two classes, minimally:
import java.awt.List;
import java.util.ArrayList;
Now, if we were to use a wildcard in the package import, we'd have the following.
import java.awt.*;
import java.util.*;
However, now we will have a problem!
There is a java.awt.List class and a java.util.List, so referring to the List class would be ambiguous. One would have to refer to the List with a fully-qualified class name if we want to remove the ambiguity:
import java.awt.*;
import java.util.*;
ArrayList<String> strings = new ArrayList<String>();
// ...
// 'List' from java.awt -- need to use a fully-qualified class name.
java.awt.List listComponent = new java.awt.List()
Therefore, there are cases where using a wildcard package import can lead to problems.
The import directive is a compiler directive, it tells the compiler where to look for a class and allows to not have to always use fully qualified class names, e.g. java.util.HashMap. But the import directives themselves do not get put into the compiled bytecode files, the compiler compiles the fully qualified name into the .class file.
When used wiithout a wildcard, the directive explicitly tells the compiler to look for one specific file in the classpath. With a wildcard, the directive tells the compiler to look for the named package and to search in that package for possible matches every time any name needs to be matched. The latter version is probably going to take (a bit) longer for the compiler than the former.
In other words, the import directive cannot affect runtime code execution in any way. However, the import directive does affect compilation time. Additionally, I find that using import with wildcards makes the code less readable.
Actually, the cost of import statements question of the month on javaperformancetuning.com perfectly summarize this in its conclusion:
There is no runtime cost from using an import statement
The compilation process can take a little more time with an import
statement
The compilation process can take even more time with a wildcard import
statement
For improved readability, wildcard import statements are bad practice for
anything but throwaway classes
The compilation overhead of non-wildcard import statements are
minor, but they give readability
benefits so best practice is to use
them
I don't believe that wildcard imports have any sort of performance implications (and if it does, I think it would only happen at compile time). But as this SO post points out, it's possible that you can have class name overlaps if you use them.
I just use Ctrl+Space to force the import when I'm using a class that hasn't been imported yet, and the import happens automatically. Then I hit Ctrl+Shift+O after I refactor a class to remove any imports that are no longer used.
Up until JDK 1.2 this code would compile fine:
import java.awt.*;
import java.util.*;
public class Foo
{
// List is java.awt.List
private List list;
}
in JDK 1.2 java.util.List was added and the code no longer compiled because the compiler did not know which List was wanted (awt or util). You can fix it by adding "import java.awt.List;" at the end of the imports, but the point is you have to do something to fix it.
I personally use the single import instead of the on-demand import for two reasons:
it is clear where each class comes
from
if you have a huge number of imports
the class is probably doing too much
and should be split up. It is a
"code smell".
From a purist point of view, every import creates a dependency and a potential for conflict. Imports are treated as a necessary evil so they are minimized. Importing another package with a * is like writing a blank check. Importing two packages like that is like giving somebody access to moving money between your accounts.
From a practical point of view, this often makes sense because different projects and libraries use surprisingly similar names for differing concepts. Or, imagine you import everything from package A and then everything from package B, and use some class C from package B. If someone later on adds a class with the name C to package A, your code might break!
That being said, I admit I'm lazy. I'll often pre-import everything in the package, and then let Eclipse organize it for me based on what I actually use.
There's no harm in importing all the classes in a package/namespace, but I think it's better to include each individual class. It makes things clearer to developers who come after you exactly where each class comes from.
It's a non-issue if you're using a capable IDE like IntelliJ. I would imagine that Eclipse and NetBeans can manage imports as well. It will add the code for you and collapse them from view so they don't clutter the window. What could be easier?
Doesn't hurt the code. As a general principle, why import something if you are not going to use?
If you write some java code such as
LinkedList<foo> llist = new LinkedList<foo>()
and you haven't imported LinkedList to your project, Eclipse will ask if you want to import it. Since you are only using LinkedList and nothing else, it will only import LinkedList. If you do something else in the same project such as
ArrayList<foo> alist = new ArrayList<foo>()
Then Eclipse will also say you need to import ArrayList, but nothing else. Eclipse only has you import what you need based on any library calls you have made. If you need multiple types or items from the same library, there isn't harm in using a
import java.namespace.*
to go ahead and bring in the other items you need. Eclipse won't care as long as you are importing the packages and libraries that contain the items you are referencing such as Scanners, LinkedLists, etc.
From a readability perspective, it's a different question. If you want people to explicitly know what exactly you are importing, then calling each widget or package might be in order. This can get rather tedious if you are using lots of different functions from the same package in the standard library and can make your file headers quite long hence the .* wildcard. There's no harm in importing via wildcard, it really boils down to your coding standards and how transparent you want your class headers to be.
Importing each class explicitly gives a hard binding between the short name (e.g. Proxy) and the long name (e.g. java.lang.reflect.Proxy), instead of the loose binding saying that there probably is one in java.lang.reflect.*, java.io.* or java.net.* or somewhere else of the wildcard imports you have.
This may be a problem if for some reason another class named Proxy shows up somewhere in java.io.* or java.net.* or your own code, as the compiler then doesn't know which Proxy class you want as it would have if you explicitly imported java.lang.reflect.Proxy.
The above example is not contrieved. The java.net.Proxy class was introduced in Java 5, and would have broken your code if it was written as hinted above. See the official Sun explanation of how to circumvent wildcard problems at http://java.sun.com/j2se/1.5.0/compatibility.html
(The wildcard import is just a convenience mechanism for those not using an IDE to maintain import statements. If you use an IDE then let it help you :)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 days ago.
Improve this question
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
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.ColorConvertOp;
2
import java.awt.*;
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!)
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.
The latter is generally considered "bad form". With tool support, there's no excuse for not listing them individually, and it removes any ambiguity.
Mind you, Eclipse by default uses wildcards for static imports, and explicit imports for normal ones. Not sure why it makes that distinction.
edit: the distinction is obvious in hindsight - static imports often refer to static methods, and you can't unambiguously refer to a static method by name (due to overloading). So if it can't be fully unambiguous, you may as well use a wildcard.
I know the question was not about performance but, the cost of import statements question of the month on javaperformancetuning.com perfectly summarize why you should avoid to use wildcards:
(...)
Finally, many people find that using
imports with wildcards makes the
source much less readable, since the
reader also needs to figure out which
package a particular class comes from,
rather than just looking it up in the
import statement.
So the full answer is
There is no runtime cost from using an import statement
The compilation process can take a little more time with an import
statement
The compilation process can take even more time with a wildcard import
statement
For improved readability, wildcard import statements are bad practice for
anything but throwaway classes
The compilation overhead of non-wildcard import statements are
minor, but they give readability
benefits so best practice is to use
them
It is a bad practice to use wilcard import statements, they make the code less readable, just don't do it. The only exception to this rule are static import, for example import static org.junit.Assert.*;. No, I don't want to import each assertXXX individually and I don't find that this harms code readability.
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.
If you use an ide like visual studio it typically takes care of this issue for you, so you don't even need to bother thinking about it.
Most IDEs that I am aware of choose option 1 above. This is consistent with some code analysis tools that I used in the past (like checkstyle), as they consider it bad practice to use the * notation.
The option 1 you listed is preferable but if there are more classes you are importing from say java.awt.image, then its preferable to just have one import java.awt.image.* Most IDE's let you specify the exact count of the number of imports to be used. For eg in IDEA, we can use File->Settings->Code Style->imports In the General tab there is a field Class count to use import with * and default value is 5.
whatever the default of your team's IDE is. that way you can just do an autoformat of your file before committing it.
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.
Import individually, it saves the compiler from having to look through each package for each class and therefore makes things run quicker.