Java does not have the concept of pointers . So how does java implement the implicitly available linkedList or even make a shallow copy for that matter ?
3 Answers
Java does have references that can point to another object, or null. That is all that is needed for a linked list.
You do the general purpose linked list in C by having a struct for node, likewise, the LinkedList would in Java contain also a private class for a node with reference to the actual value, and 1 or more references to the node class for links.
3 Comments
Java has references. These are like pointers except that you cannot do things like pointer arithmetic, or casting pointers to integers and vice-versa.
Naturally, linked lists are implemented using references.
The reasons that Java eschews pointer arithmetic and conversion between integers and pointers include:
- to eliminate a major source of bugs, and
- to make it possible to implement full-function (i.e non-conservative, non-reference counting, high performance) garbage collection.
Comments
You can certainly easily implement your own linked lists in Java. You can also use the java.util.LinkedList Class.
Here is a simple LinkedList implementation from Ivor Horton's book "Beginning Java":
public class LinkedList {
// Default constructor - creates an empty list
public LinkedList() {}
// Constructor to create a list containing one object
public LinkedList(Object item) {
if(item != null) {
current=end=start=new ListItem(item); // item is the start and end
}
}
// Construct a linked list from an array of objects
public LinkedList(Object[] items) {
if(items != null) {
// Add the items to the list
for(int i = 0; i < items.length; i++) {
addItem(items[i]);
}
current = start;
}
}
// Add an item object to the list
public void addItem(Object item) {
ListItem newEnd = new ListItem(item); // Create a new ListItem
if(start == null) { // Is the list empty?
start = end = newEnd; // Yes, so new element is start and end
} else { // No, so append new element
end.next = newEnd; // Set next variable for old end
end = newEnd; // Store new item as end
}
}
// Get the first object in the list
public Object getFirst() {
current = start;
return start == null ? null : start.item;
}
// Get the next object in the list
public Object getNext() {
if(current != null) {
current = current.next; // Get the reference to the next item
}
return current == null ? null : current.item;
}
private ListItem start = null; // First ListItem in the list
private ListItem end = null; // Last ListItem in the list
private ListItem current = null; // The current item for iterating
private class ListItem {
// Constructor
public ListItem(Object item) {
this.item = item; // Store the item
next = null; // Set next as end point
}
// Return class name & object
public String toString() {
return "ListItem " + item ;
}
ListItem next; // Refers to next item in the list
Object item; // The item for this ListItem
}
}