Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the typical convention for importing Java packages?

Tags:

java

In my programming classes in college, we would just import an entire package even if we just used one class from it. This may have been because we were supposed to use IDEs that did not offer autocompletion or anything fancy like that, so it would just make it easier to code in general.

However, now that I'm more of an experienced programmer, is it more conventional to import Java packages as a whole or just the classes from those packages that you would need?

For example, instead of:

import java.util.*;

Is it conventional to say:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

etc.?

Does importing an entire package compared to select classes use more memory?

like image 409
djmordigal Avatar asked Aug 31 '13 03:08

djmordigal


1 Answers

It's not so much a memory issue, but rather that you run the risk of inadvertently importing the wrong class if you use the * notation. Generally it's not a problem, but if the * matches a class that you meant to pull in from another package it's a hard bug to find.

I've seen IDE's use the rule that specific class imports are replaced by a single '*' import statement if you're importing three or more classes from that package. I prefer to call out each imported class by name.

like image 57
Chris Gerken Avatar answered Nov 08 '22 20:11

Chris Gerken