ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Node<T> {
T value;
Node<T> next;
Node(T v) { value = v; }
}
public class Main {
static <T> int length(Node<T> head) {
int n = 0;
while (head != null) { n++; head = head.next; }
return n;
}
public static void main(String[] args) {
Node<String> a = new Node<>("a");
Node<String> b = new Node<>("b");
a.next = b;
System.out.println(length(a));
}
}- A. 0
- B. 1
- C. 2
- D. Compile-time error: Node<T> cannot have a field of its own generic type
Correct answer: C. 2
A generic class may freely reference its own type parameter for fields, including a self-referential next : Node<T>, exactly like a non-generic linked list. length() walks from a through b, counting 2 nodes before head becomes null.
More OOP with C++ and Java questions
- What is printed? cpp struct Shape { virtual ~Shape() = default; }; struct Circle : Shape {}; struct Square : Shape {}; int main() { Shape…
- What is printed? java class Base { void process() { System.out.print("Base.process "); validate(); } protected void validate() {…
- What is printed? java class Base { public String toString() { return "Base[" + describe() + "]"; } protected String describe() { return…
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B { B() { cout << "B"; } }; struct C : A, B { C() { cout << "C"; } }; int…
- What is printed? cpp struct Animal { virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string sound()…
- What is printed? cpp struct Shape { virtual double area() const = 0; void report() const { std::cout << "Area: " << area(); } }; struct…