Java MCQs on collection framework of Java Programming Language.
1. Which of these interface declares core method that all collections will have? Answer: d 2. Which of these interface handle sequences? Answer: b 3. Which of this interface must contain a unique element? Answer: a 4. Which of these is a Basic interface that all other interface inherits? Answer: d 5. Which of these is static variable defined in Collections? Answer: d 6. What will be the output of the following Java program? a) 12345 7. What will be the output of the following Java program? a) 2 8 5 1 8. What will be the output of the following Java program? a) 2 8 5 1 (output will be different on your system)
a) set
b) EventListner
c) Comparator
d) Collection
Clarification: Collection interfaces defines core methods that all the collections like set, map, arrays etc will have.
a) Set
b) List
c) Comparator
d) Collection
Clarification: None.
a) Set
b) List
c) Array
d) Collection
Clarification: Set interface extends collection interface to handle sets, which must contain unique elements.
a) Set
b) Array
c) List
d) Collection
Clarification: Collection interface is inherited by all other interfaces like Set, Array, Map etc. It defines core methods that all the collections like set, map, arrays etc will have
a) EMPTY_SET
b) EMPTY_LIST
c) EMPTY_MAP
d) All of the mentioned
Clarification: None.
import java.util.*;
class Array
{
public static void main(String args[])
{
int array[] = new int [5];
for (int i = 5; i > 0; i--)
array[5 - i] = i;
Arrays.sort(array);
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
b) 54321
c) 1234
d) 5432
Clarification: Arrays.sort(array) method sorts the array into 1,2,3,4,5.
Output:
$ javac Array.java
$ java Array
12345
import java.util.*;
class Collection_Algos
{
public static void main(String args[])
{
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
b) 1 5 8 2
c) 1 2 5 8
d) 2 1 8 5
Clarification: Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it became 1->2->5->8.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
1 2 5 8
import java.util.*;
class Collection_Algos
{
public static void main(String args[])
{
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.shuffle(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
b) 1 5 8 2
c) 1 2 5 8
d) Any random order
Clarification: shuffle – randomizes all the elements in a list.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
1 5 2 8
