I have created a Linked List class from scratch in Java. The goal is for this Linked List class to be immutable. I am using generic types (suspected part of issue). The class has three attributes:
boolean isEmpty;
T data;
LinkedListClass<T> next;
There are also two constructors for creating this class, one is private and the other public:
private LinkedListClass(boolean isEmpty, T data, LinkedListClass<T> next){
this.isEmpty = isEmpty;
this.data = data;
this.next = next;
}
...
public LinkedListClass(){
LinkedListClass<T> newList = new LinkedListClass<T>(true, null, null);
}
The reason for this is so the user does not have direct access to the variables isEmpty, data and next. So when the user creates a Linked List, the aforementioned variables are assigned to true, null and null respectively by default. N.b. Any method that appends or changes the list in such a way that it is not empty anymore, will hence change the isEmpty value to false.
I have made a copyList() function:
public LinkedListClass<T> copyList() {
LinkedListClass<T> clonedList = new LinkedListClass<T>();
if(this.isEmpty) {
return clonedList;
}
clonedList = new LinkedListClass<T>(false, this.data, this.next.copyList() ); //this is line 32
return clonedList;
}
In the main method I am simply calling the copy function like so:
public class prog7 {
public static void main (String args[]) {
LinkedListClass<Integer> list1 = new LinkedListClass();
LinkedListClass<Integer> list2 = new LinkedListClass();
list2 = list1.copyList(); //this is line 7
}
}
Upon compiling, the following error occurs:
Exception in thread "main" java.lang.NullPointerException
at LinkedListClass.copyList(LinkedListClass.java:32)
at prog7.main(prog7.java:7)
I think the NullPointerException is thrown because when creating a LinkedListClass<T>
, two of its values are null. So when trying to change them or reference them, the exception is thrown. One workaround I have considered is replacing null in the public LinkedListClass<T>
constructor with the int value 0. However my IDE complains that the expected type is T, but I am providing it with an int. So I think this may be a question regarding type generics.