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

Discussion

The program is run with java Demo27 - what will be the output?

import java.util.*;

public class Demo27
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<String>();
        list.add("a");
        assert list.remove("a");
        System.out.println(list.size());
    }
}

  • A.Compilation fails.
  • B.The program prints 0
  • C.The program prints 1
  • D.An AssertionError is thrown.

Answer: C

This is the broken pattern quoted verbatim in the Oracle guide. The removal is the assertion's condition, so with assertions off the element is never removed and the size is still 1. The fix is to remove first, store the boolean result, and assert on that stored value.

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

Post your comment

Please log in or register to post a comment.