aspose file tools*
The moose likes Beginning Java and the fly likes Question about references Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question about references" Watch "Question about references" New topic
Author

Question about references

michael delta
Ranch Hand

Joined: Aug 11, 2009
Posts: 35

I tried the other day to refresh my reference skills in java, so I created a single linked list with a head (not a tail). While I wrote the code intuitively, I think I haven't completely understand it. Could you please clarify it in detail?

This is the code where I remove an element from the list. I can't understand the head = head.next part (head is a pseudo-node which refers to the first node). I mean, if head.next refers to the node next to the first node, why head is the reference and not the first node? Tell me if you need further clarification. Thank you.

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

So, you wrote that code, but you don't know what it does or why you wrote it that way?

Why don't you try drawing pictures of head and, say, a 3-element list, showing the data and pointers. Show what head points to and what each "next" points to. Then show what it looks like when you remove the first element. Then see if you can relate that to the code that you wrote.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14273
    
  21

In Java, variables (of non-primitive types) are always references.

Maybe you know C++. If you're used to C++, this aspect of Java can be confusing, because in C++ a variable is the object itself, not a reference.

A reference in Java is a lot like a pointer in C++ - except that you can't do pointer arithmetic.

In your code, head refers to a node object in your list. I don't know what type of object that is, since you didn't show that here. Maybe you have a class called Node that has a member variable which is a reference to the next Node. Something like this:

In your own list class, you have a member variable named head that refers to the first Node object in the list:

So, what does this line do:

It looks at the first Node in the list, takes the next reference, and makes head point to that.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
michael delta
Ranch Hand

Joined: Aug 11, 2009
Posts: 35

@ Jesper de Jong

Bingo! Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about references