2

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.

anon9928175234
  • 105
  • 1
  • 8
  • Does this answer your question: http://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad? – Pshemo Sep 19 '14 at 00:28
  • Yes it does. Thank you. I'm wondering if interviewers will not appreciate that I'm using import java.util.*? (Since I probably will be dealing with a small program) – anon9928175234 Sep 19 '14 at 00:40
  • If you are going to write code on paper then I would say using wildcards `*` is OK (you can leave comment near each one of `*` to describe which classes from this package you are going to use to show that there will be no conflict with other `*`), if you will be able to use IDE then prefer explicit imports (Eclipse can organize them for you with `Ctrl`+`Shift`+`O`). – Pshemo Sep 19 '14 at 00:44

2 Answers2

3

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.

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54
  • I've sometimes run into trouble by importing the `java.awt` and `java.util` packages with the asterisk and then attempting to use the `List` interface of the `java.util` package, forgetting that the `List` class exists in the `java.awt` package. The compiler won't be able to tell if you want to use the class/interface from one package or the other. – TNT Sep 19 '14 at 00:34
  • @TNT In that case beside `.*` wildcards you can add explicit import of `List` you want to use, like `import java.awt.*; import java.util.*; import java.util.List;` (last import will let compiler determine from which package `List` should be used). – Pshemo Sep 19 '14 at 00:37
  • @Pshemo That's a good point. I usually just put the package name in front of the class name in these situations, i.e. `java.util.List list ...` – TNT Sep 19 '14 at 00:42
0

@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.

BurningDocker
  • 133
  • 1
  • 8