Assume that you have the two classes below (a partial implementation of a linked list of Dogs). Modify them to
utilize generics (so that they can store any typed of object - instead of just Dogs). I’d suggest just writing any line that needs
to be modified to the right of the current line.
public class Node {
private Node next;
private Dog data;
public Node(Dog d) {
next = null;
data = d;
}
public Node getNext() {
return next;
}
public void setNext(Node nd) {
next = nd;
}
public Dog getData() {
return data;
}
}
public class LinkedList {
private Node head;
public LinkedList() {
head = null;
}
public void insert(Dog d) {
Node nd = new Node(d);
nd.setNext(head);
head = nd;
}
public String toString() {
String str = "";
for (Node nd = head; nd != null; nd = nd.getNext())
str += nd.getData().toString() + "\n";
return str;
}
}
//CONVERTING TO GENERIC CLASS
class Node<T> {
private Node next;
private T data;
public Node(T d) {
next = null;
data = d;
}
public Node getNext() {
return next;
}
public void setNext(Node nd) {
next = nd;
}
public T getData() {
return data;
}
}
class LinkedList<T> {
private Node head;
public LinkedList() {
head = null;
}
public void insert(T d) {
Node<T> nd = new Node<T>(d);
nd.setNext(head);
head = nd;
}
public String toString() {
String str = "";
for (Node nd = head; nd != null; nd = nd.getNext())
str += nd.getData().toString() + "\n";
return str;
}
}
Get Answers For Free
Most questions answered within 1 hours.