How do I add objects into a linked list?
Asked Answered
E

7

5

I have been working on a project where I must implement a java class that implements the use of doubly linked lists. I have the LinkedList class finished with all my methods. I'm just unsure how to actually add node objects into the list. Here is my code so far with test at the bottom. Any help would be appreciated. Thanks

public class LinkedList {

    private Node first;
    private Node current;
    private Node last;
    private int currentIndex;
    private int numElements;

    public LinkedList() {
        this.first = null;
        this.last = null;
        this.numElements = 0;
        this.current = null;
        this.currentIndex = -1;
    }

    private class Node {

        Node next;
        Node previous;
        Object data;
    }

    public boolean hasNext() {
        return (current != null && current.next != null);
    }

    public Object next() {
        if (!this.hasNext()) {
            throw new IllegalStateException("No next");
        }

        current = current.next;
        return current.data;

    }

    public boolean hasPrevious() {
        return (current != null && current.previous != null);

    }

    public Object previous() {
        if (!this.hasPrevious()) {
            throw new IllegalStateException("No previous");
        }
        current = current.previous;
        return current.data;

    }

   int nextIndex() {
        int index = numElements;
        if (hasNext()) {
            index = this.currentIndex + 1;
        }
        System.out.println(index + "The current index is " + current);
        return index;
    }

    int previousIndex() {
        int index = -1;
        if (hasPrevious()) {
            index = this.currentIndex - 1;
        }
        System.out.println(index + "The current index is " + current);
        return index;
    }

    public void set(Object o) {
        if (this.current == null) {
            throw new IllegalStateException("No node found, cannot set.");
        }
        current.data = o;
    }

    public int size() {
        return numElements;
    }

    public void add(Object o) {       
        Node newNode = new Node();
        newNode.data = o;
        if (first == null) {
            first = newNode;
            last = newNode;
            newNode.next = null;

        } else if (first != null) {
            if (current == null) {
                newNode.previous = null;
                newNode.next = first;
                first.previous = newNode;
                first = newNode;
            } else if (current == last) {
                newNode.previous = current;
                newNode.next = null;
                current.next = newNode;
                last = newNode;
            } else {
                newNode.previous = current;
                newNode.next = current.next;
                current.next.previous = newNode;
                current.next = newNode;
            }
        }
        current = newNode;
        numElements++;
        currentIndex++;

    }

    public void remove() {
        if (current != null) {
            if (current == first && current == last) {
                first = null;
                last = null;
            } else if (current == last) {
                current.previous = null;
                last = current.previous;
            } else if (current == last) {
                current.previous.next = null;
                last = current.previous;
            } else {
                current.previous.next = current.next;
                current.next.previous = current.previous;
            }
            current = current.next;
            numElements--;
        }
    }
}



import java.util.Scanner;


public class LinkedListTest {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String name;
        int index;

        LinkedList<Object> listOne = new LinkedList<Object>();

        listOne.add(object o);

    }
}
Efface answered 7/3, 2013 at 22:26 Comment(8)
Sorry about the test class I'm aware it's disgracefulEfface
Looks like you're on the right track so far. What does your output give you and what are you expecting to get?Eristic
Where is the object newNode coming from in listOne.add(newNode)? Also you really should look at using generics.Culverin
I don't get out put the error reads "Type LinkedList does not take paramaters"Efface
Sorry that shouldn't be newNode, it should be Object oEfface
@Efface it's because your LinkedList is not generic, so you can't paramterize it with <Object>Culverin
Joe, I would suggest renaming your LinkedList class since so it doesn't match the built in java LinkedList.Eristic
@Johannes Weiß: please look at the homework tag wiki.Dopey
K
4

The posted class LinkedList looks functional to me.

Make sure that your test code does not confuse this class and java.util.LinkedList, which Java provides for you (It's a part of the existing Collections framework).

For clarity, I would recommend renaming your class to something like MyLinkedList

The following code works and the output is "0","2":

public class MyLinkedListTest {

    public static final void main(String[] args) {

        MyLinkedList list = new MyLinkedList();
        System.out.println("Number of items in the list: " + list.size());

        String item1 = "foo";
        String item2 = "bar";

        list.add(item1);
        list.add(item2);

        System.out.println("Number of items in the list: " + list.size());      

        // and so on...
    }

}
Kaveri answered 7/3, 2013 at 22:55 Comment(1)
This seems like the best way to go about it. ThanksEfface
C
2

I'd be surprised if your code compiled, since your class isn't actually generic. Just initialize it as LinkedList listOne = new LinkedList(); (no angle brackets).

As to actually adding elements, you just need an instance of some Object to add; anything will do (assuming your internal code works properly). Try this down at the end there:

Object objectToAdd = "Strings are Objects";
listOne.add(objectToAdd);
objectToAdd = new File("C:\\foo.bar"); // Or use any other Objects!
listOne.add(objectToAdd);
Christopher answered 7/3, 2013 at 22:34 Comment(3)
I caught this too. He may want to be careful as some IDEs will automatically import the Java LinkedList which would cause confusion.Eristic
@Eristic I'm assuming he's not using an IDE, or it would have warned him that listOne.add(object o); won't compile, but that's certainly a valid concern.Christopher
That's true, but if he's new to coding he may well have typed through the warning without noticing.Eristic
S
1

Think of numbered list and look at the relations between the elements

Say I have the list:

  1. A
  2. B
  3. C

What do I have to do to the relations get the list:

  1. A
  2. B
  3. NewNode
  4. C

The new next node of B is NewNode The new previous node of C is NewNode. So an insert function would want to know the immediate previous node or the immediate next node and then adjust the relationships.

Sicular answered 7/3, 2013 at 22:34 Comment(3)
How does this pertain to his question?Christopher
@HenryKeiter "How do I add objects into a linked list?" It's clearly homework, therefore I explained how in English, not code.Sicular
He already has the code. He's asking literally how to instantiate the list and add objects to it. It's a syntax question, not implementation.Christopher
I
1

Your LinkedList doesn't have generic types so you can't declare it as

LinkedList<Object> listOne = new LinkedList<Object>();

but rather as

LinkedList listOne = new LinkedList();

And now to add elements just use your add method

listOne.add("something");
listOne.add(1);//int will be autoboxed to Integer objects

Also if you want to add data from keyboard you can use something like

String line="";
do{
    System.out.println("type what you want to add to list:");
    line = keyboard.nextLine();
    listOne.add(line);
}while(!line.equals("exit"));
Impassable answered 7/3, 2013 at 22:37 Comment(2)
This works and I had similar code before but if I use the String "Something" or the int 1 are they considered objects?Efface
@Efface String is a class, and all classes at some point extend Object class so their instances can be threated as Objects. In case of 1 it is primitive type int, but in this case when you use primitive type as parameter that was expecting Object it will be autoboxed to Integer which also extends at some point Object so it will work.Impassable
T
0

The line

LinkedList<Object> listOne = new LinkedList<Object>();

won't compile unless you change your class declaration to

class LinkedList<T>

or alternately you can just write

LinkedList listOne = new LinkedLis();

After that you should be able to add objects to your list. However, you'll need to create an Object to add to it, listOne.add(object o); won't do--at the very least you'll have to write listOne.add(new Object()). (Your code does not instantiate an Object, there is no Object that you already have called o, and besides, object o does not mean anything in Java and would not compile.

Tertial answered 7/3, 2013 at 22:41 Comment(3)
I understand. So if I create a class, say Car for example. Would I have to create a new car each time or could I use my default constructor to just add multiples of the same default car into the list?Efface
You can certainly add multiples of the same default car into the list, but what are you trying to achieve exactly? Why do you want to have a list of the same exact car object?Tertial
More to the point, if you add the same instance of an object into your list multiple times, how will you verify, for example, that objects are being added correctly, in the correct order? All the objects in your list will look identical and you won't be able to garner any information from that at all.Tertial
C
0

As people have mentioned your list is not generic. However as they advise you to get rid of the parameter, you can also just add <Object> or <E> to your linked list implementation and leave your initialization of the list as it is.

So in your linked list class you should do something like:

public class LinkedList<E>

This will make sure when you're using LinkedList<Object> listOne = new LinkedList<Object>();, E will be covnerted to Object

Culverin answered 7/3, 2013 at 22:42 Comment(0)
E
0

Let's improve your test a little bit so that it becomes apparent where your problems are (if any) I commented out the call to the current() method since you have not included one. (I would leave this alone as it may confuse you.) The general idea would be to add items to the linked list and walk forward and backward through it checking the items with each step.

public class LinkedListTest {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String name;
        int index;

        LinkedList listOne = new LinkedList();
        //Initially we should be empty so we are positioned
        // at both the beginning and end of the list
        assert listOne.size() == 0 :"List should be empty";
        assert listOne.hasPrevious()==false: "Should be at the beginning of the list";
        assert listOne.hasNext()==false : "Should be at the end of the list";

        Object firstNode = "I am the first node";
        listOne.add(firstNode); //we've added something
//I left this commented out since you don't have a current() method.
//        assert firstNode == listOne.current() : "Our current item should be what we just added";
        assert listOne.hasPrevious()==false : "Should not have moved forward in our list yet";
        assert listOne.hasNext()==true : "should have an item after our current";
        assert listOne.size() == 1 : "Should only have one item in the list";
        Object secondNode = "I am the second node";
        listOne.add(secondNode);
        assert listOne.size() == 2 : "Should only have two items in the list";

        assert firstNode == listOne.next() : "1st call to next should return the 1st node";
        assert listOne.hasPrevious()==true : "We should be positioned after the 1st node";
        assert listOne.hasNext()==true : "We should be positioned before the 2nd node";
    }
}
Eristic answered 7/3, 2013 at 22:47 Comment(2)
Is the use off Assert common practice in Java?#Efface
It depends on where you're employed! :D I use asserts here to illustrate how the code is intended to work. Many folks would use the full framework of JUnit to do the same. Either way you get the benefit of debugging your code without using a debugger, an incremental approach to solution discovery, and built-in documentation that never falls out of date.Eristic

© 2022 - 2024 — McMap. All rights reserved.