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

Discussion

What will be the output of the program?

import java.util.*;

public class Sample23
{
    public static void main(String[] args)
    {
        List<String> roles = new ArrayList<String>();
        Collections.addAll(roles, "admin", "editor", "viewer");
        String previous = roles.set(1, "author");
        System.out.println(
            previous + " -> " + roles.get(1) + " size " + roles.size());
    }
}

  • A.null -> author size 3
  • B.author -> editor size 3
  • C.editor -> author size 3
  • D.editor -> author size 4

Answer: C

set replaces the element at the index and returns whatever was there before, so previous holds editor while position 1 now holds author. The size is unchanged at 3 because nothing was inserted. Returning the displaced value is what distinguishes set from the two-argument add, which shifts and grows the list.

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

Post your comment

Please log in or register to post a comment.