Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing List<E>: do I need a new class?

First of all, i have been studying Java for only the last couple of weeks, so I don't have much experience yet.

This is more of a theoretical question. I want to create a simple list.

So first I made a class where I specified some methods. I want it to be generic so I can use any type.

  public interface List<E> 

Now i need to implement it, so i created:

    public class MyList<E> implements List<E>

Now, I need two attributes:

 private E element;
 private MyList<E> next;

One will hold my generic type, the other will be the link to the next element. First of all, I don't know if it's the correct way to write it. And if i leave this attributes inside this class, will it work properly?

Second of all, I have been thinking whether it's better to create another class, lets say a Box class, that will contain these two fields, thus making manipulation easier during my implementation.

Might be a silly question, but I am trying to learn and to understand the best ways to do this.

Thanks for your time.

like image 946
Alessandroempire Avatar asked Jul 20 '26 08:07

Alessandroempire


1 Answers

I guess you are trying to implement a singly-linked list. Now to answer your question, I think that it would be beneficial for you to create a Box class like you mentioned (often called Node). So your implementation might look like this:

public class MyList<E> implements List<E> {
    private Node<E> head;

    private static class Node<E> {
        private E element;
        private Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }

        // ...
    }

    // ...
}

MyList would hold a single Node that is connected to a chain of other Nodes. If you take a look, this is how the the actual java.util.LinkedList class is written.

like image 194
arshajii Avatar answered Jul 21 '26 21:07

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!