GenericsExercise Convert the Node class in the following file to be generic. pub
ID: 3760439 • Letter: G
Question
GenericsExercise Convert the Node class in the following file to be generic.
public class Node {
protected String item; protected Node next;
Node( String itemArg ) { item = itemArg;
next = null;
}
Node( String itemArg, Node nextArg ) { item = itemArg;
next = nextArg;
}
public static void main( String [] args ) {
Node firstNode = new Node(new String("last")); firstNode = new Node(new String("middle"),firstNode); firstNode = new Node(new String("first"),firstNode);
for (Node current = firstNode; current != null; current = current.next) {
System.out.println((String)current.item + ' ');
}
}
}
Edit this file so that Node is a generic class with a parameterized type for item. Test it by creating a node to hold a String, like in the orignal code. Then test it by creating a node that holds items of type Integer, the int wrapper class.
public class Node {
protected String item; protected Node next;
Node( String itemArg ) { item = itemArg;
next = null;
}
Node( String itemArg, Node nextArg ) { item = itemArg;
next = nextArg;
}
public static void main( String [] args ) {
Node firstNode = new Node(new String("last")); firstNode = new Node(new String("middle"),firstNode); firstNode = new Node(new String("first"),firstNode);
for (Node current = firstNode; current != null; current = current.next) {
System.out.println((String)current.item + ' ');
}
}
}
Explanation / Answer
public class Node<T> {
protected T item;
protected Node<T> next;
Node(T itemArg) {
item = itemArg;
next = null;
}
Node(T itemArg, Node<T> nextArg) {
item = itemArg;
next = nextArg;
}
public static void main(String[] args) {
System.out.println("Strings: ");
Node<String> firstNode = new Node(new String("last"));
firstNode = new Node(new String("middle"), firstNode);
firstNode = new Node(new String("first"), firstNode);
for (Node current = firstNode; current != null; current = current.next) {
System.out.println((String) current.item + ' ');
}
System.out.println(" Integers: ");
Node<Integer> fN = new Node(3);
fN = new Node(2, fN);
fN = new Node(1, fN);
for (Node current = fN; current != null; current = current.next) {
System.out.println(current.item);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.