Celeritas
Celeritas

Reputation: 15091

Implementation of linked list in Java

During an interview I was asked to implement some linked list methods in Java. I've only had experience implementing linked list in C++ and there were somethings that concerned me. After having read this question and seeing the answer, I still have concerns.

class Link {
    public int data1;
    public double data2;
    public Link nextLink;

    //Link constructor
    public Link(int d1, double d2) {
        data1 = d1;
        data2 = d2;
    }

    //Print Link data
    public void printLink() {
        System.out.print("{" + data1 + ", " + data2 + "} ");
    }
}

My first problem is Java doesn't have pointers. I'm used to seeing something like Node* nextNode; instead of public Link nextLink;. How can a value be assigned to Link without pointers? Is it because in Java new returns an actual Link object? Or does it return a reference to it? If it returns a reference to it isn't that a problem since a reference is different than an actual Link object? Or in Java is any object's identifier actually a reference?

I know this is a matter of opinion, but why is it that linked lists seem to occur more in C++? I guess the language doesn't have built in support so a lot of tutorials written about linked lists are geared towards C++ (even if the focus was on the data structure).

Upvotes: 0

Views: 734

Answers (4)

Yogesh
Yogesh

Reputation: 563

The object references in java are just as good as pointers, the noticeable difference is that you cannot do pointer arithmetic here. MyClass myRef;in java just means a reference that will be pointing to some object. when you do MyClass myRef = new MyClass(); an object and created and its reference is stored in myRef. You should realize the difference between objects in memory and their reference in myRef. It is pretty much same as what we do in C/C++.

Upvotes: 0

anirudh
anirudh

Reputation: 4176

In java, the objects are manipulated by their references, and a reference is similar to the pointer in C++, except that you won't be able to actually manipulate the addresses directly as you do in C++.

In java, when you use an Object, you use its reference, and hence the Link in your code is just a reference to the next Node object in the list.

Upvotes: 0

Haris Mehmood
Haris Mehmood

Reputation: 902

Java has its own LinkedList Class, if thats what you are asking for

check here:

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Upvotes: 0

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

It's cause java manipulates objects with their references. It's well known that java is pass by value, however the value of the objects is their addresses.

Upvotes: 1

Related Questions