tags:

views:

373

answers:

4

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?

+6  A: 

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.

fastcodejava
Why? What's the advantage?
Dustman
+7  A: 

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.

tulskiy
++. The compiler is good about only importing classes that actually get used, so the only advantage to importing particular classes is keeping down the probability of unqualified name collision.
Dustman
One specific example is if you import java.awt.* and java.util.* and then try to use List. In this case you have to import specific class.
tulskiy
+13  A: 

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.

Jon
+1 I nominate this answer for acceptance.
Drew Wills
@Jon - thanks for your input, what namespace collision can cause? compiler will return error?
Registered User
e.g. If you use Date date = new Date(); and import java.util.* and import java.sql.* you'll end up with a syntax error for "The type Date is ambiguous".
Jon
+6  A: 

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

akf