Java Java Data Structures Exploring the Java Collection Framework Sets

Siu KWAN Yuen
PRO
Siu KWAN Yuen
Pro Student 2,896 Points

import packages

Is java.util.HashSet a "sub" package of java.util?

If I need to import HashSet Class, can I import java.util.* instead?

4 Answers

Gabe Olesen
Gabe Olesen
1,606 Points

Hey Siu,

You can use import java.util.*; however as Craig said it's considered "lazy" and bad practice to some. When we get onto IDE's they will automatically import e.g. java.util.HashSet; if you use it. I would advise to import them individually as you use them as it get's you into the rhythm of doing it yourself and understanding why you're doing it.

~Gabe :coffee:

Siu KWAN Yuen
PRO
Siu KWAN Yuen
Pro Student 2,896 Points

Thanks Gabe. So if I want to import "PackageABC.XYZ", I can import "PackageABC.*" instead. But I am confused about if "PackageABC.XYZ" is inside the package of "PackageABC".

I found the following in java Oracle website and don't really understand what it means. https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html /* At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt. However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. */

Gabe Olesen
Gabe Olesen
1,606 Points

Maybe this will explain it better than the official documentation:

Before you read this: import.java.util.*; is referred to as "wildcard".

The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:

  1. You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
  2. You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
  3. When you compile your code there is no com.mycompany.calendar.Event, but when they later add one your previously valid code suddenly stops compiling. The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.

Source: https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad