Skylion
Skylion

Reputation: 2752

Which is a better way of writing code? Specific constructors or imports

I was just curious which is the preferred way of coding as I've seen code written both of these ways.

import java.util.ArrayList;
import java.util.List;
 /**
 *Rest of code
 */
 List<Blah> blahs = new ArrayList();

or

import java.util.List;
 /**
 *Rest of code
 */
 List<Blah> blahs = new java.util.ArrayList();

So, which is preferred and why? What are the advantages & disadvantages of both methods? Just curious.

Upvotes: 2

Views: 79

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213261

So, which is preferred and why?

First one should be prefered. Code clarity is the most important concern.

What are the advantages & disadvantages of both methods?

Well, compiler will anyway convert the first approach to the later one, by replacing all the classes and types, with their fully qualified names. Both the codes would lead to the same byte code. As such you should really not bother about these stuffs. (You can check the byte code by running javap command)

The only reason you would use the fully qualified name is to resolve name clashes in different packages that you have imported. For e.g., if you are importing both java.util.* and java.sql.*, then you would need to use fully qualified name of Date class.

Related post:

Upvotes: 5

Josh M
Josh M

Reputation: 11937

Probably the former because the latter looks kind of obscure. You should only use the latter (specifying package names before classes) if you are using multiple classes found in different packages.

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

  • Fully-qualified names are preffered when you have several classes with the same simple name.

  • In all the other cases, the preffered and easy-to-read approach would be importing the fully-quallified name and using the simple class names.

Upvotes: 3

Related Questions