Question: Correct the generics-related errors in both classes so that the List works as expected. Besides, there also seems to be a bug in the toString
Correct the generics-related errors in both classes so that the List works as expected. Besides, there also seems to be a bug in the toString - Method
the expected output:
the length of the list is: 3 the first element is: Hello the element with index 2 is: ! the last element is: ! the whole list is: Hallo -> Welt -> ! -> and again the whole list is: Hallo -> Welt -> ! -> public class List { private class Node { private T element = null; private Node next = null; private Node(T element, Node next) { this.element = element; this.next = next; } private Node(int element) { this.element = element; } } private Node head = null; public void prepend(int object) { head = new Node(object, head); } public void append(T object) { if(head == null) { head = new Node(object); return; } Node current = head; while(current.next != null) { current = current.next; } current.next = new Node(object); } public T first() { return get(0); } public int get(T index) { Node current = head; for(int i = 0; i < index; i++) { current = current.next; } return current.element; } public int size() { Node current = head; int size = 0; for(; current != null; size++) { current = current.next; } return size; } public String toString() { String string = ""; while(head != null) { string += head.element + " -> "; head = head.next; } return string; } } public class ListPlayground { public static void main(String[] args) { List stringlist = new List()<>; stringliste.append("World"); stringliste.append("!"); stringliste.prepend("Hello"); System.out.println("The length of the list is: " + stringlist.size()); System.out.println("the first element is: " + stringlist.first()); System.out.println("the element with index 2 is: " + stringlist.get(2)); System.out.println("the last element is: " + stringlist.get(stringlist.size() - 1)); System.out.println("the whole list is: " + stringlist.toString()); System.out.println("and again the whole list is: " + stringlist.toString()); } }
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
