Menu
Topics Index
...
`

Generic Collections


If you need explanation Read this topic

If you need Answer Take test on this topic

Generic Collections
What will be the output of the following program?
import java.util.*;
public class AddStrings<T> {
    String add(Collection<?> obj) {
        String result = "";
        for (Object o : obj)
            result += o;
        return result;
    }
    public static void main(String args[]) {
        List<?> numbers = Arrays.asList(1, 2, 3);
        System.out.println("Sum = " + new AddStrings().add(numbers));
    }
}

A. Sum = 6
B. Sum = 123
C. Some other output
D. Compilation Error or Runtime Error
Topic: Why Collections Are Generic In Java?

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans : B ,numbers list is sent as a collection object. Iterating over in add function, when collection elements are added as objects, they are concatenated as strings (Object.toString()) instead of getting added and returned as string.

Posted by Pooja Donekal    2014-05-22 05:02:52


Congratulations Pooja Donekal. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-05-23 04:50:53


© meritcampus 2019

All Rights Reserved.

Open In App