How to import java class? [duplicate]
Possible Duplicate:
Import package.* vs import package.SpecificType
Can I do:
import java.awt.*
instead of:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
if both ways are correct which one is better?
You can import the general package, but it's better to be more explicit and import the specific classes you need. It helps to prevent namespace collision issues and is much nicer.
Also, if you're using Eclipse and the shortcut CTRL+SHIFT+O it will automatically generate the explicit imports, prompting you for the ambiguous imports.
It will import only classes in java.awt, so you have to import java.awt.event too:
import java.awt.*
import java.awt.event.*;
Second method will probably load less classes, but won't save you much memory.
They are both good. The top one is less verbose, but the second will allow you to be specific about the classes you import, allowing you to avoid collisions. As most IDEs will allow you to hide import statements, the verbosity of the second is not really an issue.
Consider
import java.util.*;
import java.awt.*;
when you try to declare a List
, you will have a collision between java.awt.List
and java.util.List
One that is more explicit.
EDIT : Advantage of the second method is readability, no conflict of namespaces, etc. But if you have hundred classes to import from one package you better go with the first approach.
精彩评论