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.
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
Boxclass like you mentioned (often calledNode). So your implementation might look like this:MyListwould hold a singleNodethat is connected to a chain of otherNodes. If you take a look, this is how the the actualjava.util.LinkedListclass is written.