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..
You add a boolean field to the list class, maybe named allowModifications. Initially, that field is true, but you add a method maybe called seal() to your class that changes that field to false.
And then all your methods that would change the list simply check that field. If true, they do what they should do, otherwise they could throw an exception telling the user that modifications aren't allowed for sealed lists.
Another approach could be you define a special instance of your node class. And when seal() gets called you have the last element in the list point to that special value instead of null to mark: adding other elements is no longer allowed. But the solution based on that flag is less complicated.
Given the comment by the OP: the real world solution works differently: you basically have list that allow modifications, all the time. And then you a separate list implantation that can't be modified after its initial creation. You create that list based on another list, it fetches the elements in there, and then simply refuses any kind of modification.
And no, a list class cannot know whether instances of itself are marked as final!