Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

linked list - What is the preferred way of writing a loop in Java. Please have a look at the code below

I am trying to add a node (newNode) to the end of a linked list and for that, I am trying to traverse to the end of the linked list.

My preferred way is by creating a reference to the head of the list and then parsing till we reach the last element. For this, I normally use the while loop.

Node ptr = head;
while (ptr.next != null) {
   ptr = ptr.next;
}
ptr.next = newNode

I came across this for-loop which achieves the same

Node p, q;
for (p = head; (q = p.next) != null; p = q);
p.next = newNode;

I am used to Python and the"pythonic" way of coding. Hence, I am wondering does Java have a more preferred way? and which amongst the two methods above would be preferred by an experienced Java developer?

question from:https://stackoverflow.com/questions/65856290/what-is-the-preferred-way-of-writing-a-loop-in-java-please-have-a-look-at-the-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Though this is a subjective question, everyone (or most) would agree that the second option is not readable. I missed to notice the ; at the end.

Make your code readable and easy to understand. Don't make it look smart.

Note: This doesn't mean that you should not use a for loop. Make the for loop equivalent to the while loop.

for (Node ptr = head; ptr.next != null;) {
    ptr = ptr.next;
}

Or, at least add an empty body {} to your for loop code.

for (p = head; (q = p.next) != null; p = q) {
}

I have seen static code analyzer rules set to up fail the compilation/build when loops have an empty body (explicit like above or when using a ; at the end as in your question).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...