Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 903
Skylion Avatar asked Dec 10 '25 21:12

Skylion


2 Answers

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:

  • Does an unused import declaration eat memory, in Java?
like image 145
Rohit Jain Avatar answered Dec 13 '25 12:12

Rohit Jain


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

like image 30
Konstantin Yovkov Avatar answered Dec 13 '25 10:12

Konstantin Yovkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!