I am training my Java skills and currently im working on my own linked list implementation. Here I want to create a linked list in which you cant add or delete listitems. Unfortunately I'm still able to add Listitems.
So how should i design those classes when I want to make a final instance of List.
public class ListElement {
private int data;
private ListElement nextElement;
}
public class List {
private ListElement first = null;
public List() {
first = null;
}
public static List randomList(int numListElements) {
List list = new List();
for(int i = 0; i < numListElements; i++)
{
list.add((int) ((Math.random() * 100) + 1));
}
return list;
}
public void add(int d1) {
if(first == null)
{
first= new ListElement(d1);
return;
}
ListElement currentLink = first;
while(currentLink.getNextElement() != null)
{
currentLink = currentLink.getNextElement();
}
currentLink.setNextElement(new ListElement(d1));
}
}
public class Listentest {
public static void main(String[] args) {
final List list = List.randomList(3);
System.out.println(list.toString());
list.add(5);
System.out.println(list.toString());
}
}
In the first output i receive 3 elements. In the second output i receive 4 elements. I want the output to be the same..