Just to know. Which is the proper way of ordering import statements? Also which has more readability?
like,
- External classes (like
java.util.List
) and then internal package
classes. - Just in alphabetical order
Thanks in advance.
Just to know. Which is the proper way of ordering import statements? Also which has more readability?
like,
java.util.List
) and then internal packageThanks in advance.
I prefer alphabetical order - this is the most readable, isn't it...
Most of the IDEs does this Job nicely. Just right click and say "Organize Imports".
As others have mentioned, if you're using an IDE like Eclipse or IntelliJ, readability isn't too much of a concern because you start to trust that the organization is automated and perfect.
The one area, then, where order does matter, is defining the precedence if you have multiple classes with the same name potentially imported via a
.*
notation.For example, say you have
java.util.List
andorg.northpole.christmas.List
available and you specify importsjava.util.*
andorg.northpole.christmas.*
Then in this case it makes sense to havejava.util.*
higher thanorg.northpole.christmas.*
because if I wasn't really paying that much attention and I was reading the code later, I would assume thatList
isjava.util.List
and not something else. This is why, I believe, Eclipse hasjava
andjavax
first, thenorg.apache
, then others. These days I also slipcom.google
in above or beloworg.apache
.I just use the default order that my IDE (Eclipse) implements ... and regularly run the "Tidy Imports" thingy to keep the house in order.
Readability is not a significant concern if you automate this. You will quickly get used to any automated ordering, no matter what it is. Besides, people tend not to read imports anyway.
From the Java Programming Style Guidelines
Refere the Java Tutorial link for more info.
Most preferred, and used in most IDE, is alphabetical ordering, starting from domain level and a fully qualified class name.
java.*
andjavax.*
takes precedence, and the rest are ordered.Example: