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 :)
Related
I was working on a little Java program and was using arrays so I had done:
import java.util.Arrays;
Later I started expanding on what I had previously done and decided I wanted to get input from the user, so at that point I added:
import java.util.Scanner;
Now a thought occurred. I know that I could just do:
import java.util.*
Then I'd just need 1 import line instead of two (or however many I end up needing), but does the wildcard in the import mean that it will import everything from that package regardless of if it's needed or not, or will only the selective functionality be pulled?
My instinct here is to write more code and only include the packages I know I need, but if it doesn't make a difference why would anyone import more levels/packages then they need to? (I'd rather just be lazy and write less code)
Be clear about what import is doing. It does NOT mean loading .class files and byte code.
All import does is allow you to save typing by using short class names.
So if you use java.sql.PreparedStatement in your code, you get to use PreparedStatement when you import java.sql.PreparedStatement. You can write Java code forever without using a single import statement. You'll just have to spell out all the fully-resolved class names.
And the class loader will still bring in byte code from .class files on first use at runtime.
It saves you keystrokes. That's all.
It has nothing to do with class loading.
Personally, I prefer to avoid the * notation. I spell each and every import out. I think it documents my intent better. My IDE is IntelliJ, so I ask it to insert imports on the fly.
Laziness is usually a virtue for developers, but not in this case. Spell them out and have your IDE insert them for you individually.
if you type
import java.util.*;
you'll get to refer to Scanner and List by their short names.
But if you want to do the same for FutureTask and LinkedBlockingQueue you'll have to have this:
import java.util.concurrent.*;
The wildcard imports everything in that package. However, use an IDE like Eclipse and it offers you the possibility to organize the imports.
The wildcard imports all classes and interfaces in that package.
However, the wildcard import does not import other packages that start with the same name.
For example, importing java.xml.* does not import the java.xml.bind package.
In Java, imports are related to an (outer) class, as every (outer) class is supposed to be coded in a separate file. Thus, one could claim that the import ...; directives before a class definition are associated with the class (somewhat like annotations are).
Now, if one could inherit a parent class' imports, that would greatly reduce the clutter of source files. Why should this not be possible? i.e. why should the Java compiler not consider also the imports of base classes?
Notes:
There's probably more than one answer.
I know this is not much of an issue if you let eclipse organize your imports, no need to mention that. This is about the 'why', not the 'how' (a-la-this).
Firstly, it is important to note that not every class must be coded in a separate file - but rather that every public, top level class must be. And no, imports are not really associated with any class - they are just statements used to include certain external classes / packages within a file so that they can be used. In fact, you never need to actually import anything, you can always use the full name, i.e.:
java.util.List<String> list = new java.util.ArrayList<String>();
Imports are there for convenience (and only for the compiler - they are lost after the class is compiled), to save you from having to write all that out and instead only make you write List<String> list = new ArrayList<String> (after you make the relevant imports from java.util). Consequently, there is no reason why subclasses should 'inherit' imports.
Imports are syntactic sugar, nothing more. You could write any Java program without ever using an import statement if you really wanted to. For example, the following class compiles all by itself:
class Foo {
java.util.List<String> list = new java.util.ArrayList<String>();
}
Additionally, inheriting imports makes it much, much harder to remove an import from a class. For example, if Bar.java inherits from Foo.java, you might not be able to remove an import from Foo without adding it to Bar. Forcing imports to be explicit makes it significantly easier to change a single file without worrying about the effects on other files, which is pretty much a fundamental principle of Java and object-oriented programming generally.
(This last point is related to issues that were a significant factor in the design of Go, which was specifically attempting to avoid the problems with C and C++ in this area.)
Having each file explicitly specify its imports improves readability. Imagine opening a file and not being able to see the dependencies at a glance, because the imports are inherited from another file.
Let's say, I have the following structure:
src.main.java
first
one.java
two.java
three.java
second
alpha.java
beta.java
gamma.java
I want all classes from first package to be imported in all classes in my second package.
Now I'm just specifying for every class in second package:
import first.*;
Can I import once for all classes in package?
No, it cannot be done.
I don't see why this is such a hardship.
A better solution would be to use an IDE that can add the imports as you need them.
I'd also recommend spelling each one out individually rather than using the star notation, even if you need to import all of them. It documents your intent better, and that IDE can make it transparent to you.
No, you can't do that in Java.
One thing that you might think of doing is moving classes from second package to first so you won't need the imports. But I understand that that is not always possible/desirable.
Can I import once for all classes in package?
No you can't. Imports only apply to the class source file in which they are declared.
Maybe I can create some superclass with import statements and then extend it every time?
That will only work if the code in the subclasses does not mention the names of the external types at all ... which is rarely possible.
As I said imports only apply to the class source file in which they are declared.
Actually, the import was deliberately designed to work this way. The idea is to allow you to easily figure out what class a classname refers to. (It works best if you don't use star imports ...)
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is using a wild card with a Java import statement bad?
Ex. 1
import javax.swing.*
JFrame f = new JFrame()
Ex. 2
import javax.swing.JFrame
JFrame f = new JFrame()
Is there any efficiency gain (even the slightest and minimal) in adapting 2) instead of 1) ? How does java does the referencing of packages internally?
The first time the compiler comes across the word JFrame, I presume that it should search for JFrame in complete swing.* package in case of 1)..Else if in case 2), it might probably get hold of the class directly by some indexing or may be key value hashing? So why is this not considered an efficiency gain even if it is tiny? (Please correct me if my presumptions about the internals are wrong)
EDIT :
Sorry for the duplicate.. Answer at Why is using a wild card with a Java import statement bad?
There is no runtime penalty for using import javax.swing.*
and import javax.swing.JFrame in Java. The only different is in compile time, the import package.* will search for whole package to find the correct class' information.
The Single-Type-Import (e.g., import javax.swing.JFrame) increases the readability of the program and it will be very clear which classes have been used.
The Type-Import-on-Demand (e.g. import javax.swing.*) causes the simple names of all public types declared in the package javax.swing to be available within the class and interface declarations of the compilation unit.
the first one will load all classes in the package at the compile time
Ex : 1
import javax.swing.*
JFrame f = new JFrame()
the second will load only class specified at the compile time
Ex: 2
import javax.swing.JFrame
JFrame f = new JFrame()
it will increase the compile time if you use the first approach
The star notation is merely a convenience so you as a programmer don't have to write tons of import statements. The star notation will include all classes of the specific package as a compilation candidate.
Note that in most cases being specific is preferred as it will clearly expresses your intention. Furthermore, modern IDE's will do the tedious bit of import statements for you. So in a way you can consider the star notation rather obsolete.
It has performance issue at compile time as others said (may not be very significant one considering the processing power of current computers). ie., importing * make the compiler need to look in entire package, while importing a specific class allows the compiler to fetch it directly. But it doesn't cause any performance issues at run-time, because all classes will be correctly linked by the compiler after compilation.
It also has something to do with readability. If we import javax.swing.*, it will be difficult for us to know which classes are being used from the package javax.swing. We need to read the program to find it out. But, if we import specific classes like import javax.swing.JFrame, it will help the reader to understand only the specified classes are being used from outside packages. Here we know that only JFrame is used from the package javax.swing without reading the entire program. ie., the one can find the dependencies required by our program easily by looking at the import section.
Another problem is that you may get into naming conflicts. For example, if you do two imports import com.abc.* and import com.xyz.*. Now, assume that both packages contain a class named SomeClass. Then, it put the compiler into an ambiguous situation as to which SomeClass to be imported, and thus it will result in a compile time error.
Apart from that Ex.2 is more explicit and thus clearer, it's also more stable/ compatible.
E.g. consider
import java.awt.*;
import java.util.*;
...
List list;
in pre-collection days. If you run the same code with a jdk version which has collections, the compiler complains as it doesn't know which List to use.
As others said, IDEs will help you organize the import statements.
Yes.
import javax.swing.*
imports all classes within this package.
import javax.swing.JFrame
imports only JFrame class.
I would suggest importing concrete classes.
Regards!