Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Example19
{
    static class Box { int v = 1; }

    public static void main(String[] args)
    {
        List<Box> l = new ArrayList<Box>();
        l.add(new Box());
        System.out.println(l.contains(new Box()));
    }
}

  • A.Compilation fails.
  • B.The program prints true
  • C.The program prints false
  • D.The program prints 1

Answer: C

Box does not override equals, so it inherits identity comparison from Object and no two separately created boxes are ever equal. contains searches by equality and therefore returns false, even though the field values match. Overriding equals is what would make this true.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.