Java MCQs on collection algorithms of Java Programming Language.
1. Which of these is an incorrect form of using method max() to obtain a maximum element? Answer: c 2. Which of these methods sets every element of a List to a specified object? Answer: b 3. Which of these methods can randomize all elements in a list? Answer: c 4. Which of these methods can convert an object into a List? Answer: c 5. Which of these is true about unmodifiableCollection() method? Answer: b 6. What will be the output of the following Java program? a) 2 8 5 1 7. What will be the output of the following Java program? a) 2 8 5 1
a) max(Collection c)
b) max(Collection c, Comparator comp)
c) max(Comparator comp)
d) max(List c)
Clarification: Its illegal to call max() only with comparator, we need to give the collection to be searched into.
a) set()
b) fill()
c) Complete()
d) add()
Clarification: None.
a) rand()
b) randomize()
c) shuffle()
d) ambiguous()
Clarification: shuffle – randomizes all the elements in a list.
a) SetList()
b) ConvertList()
c) singletonList()
d) CopyList()
Clarification: singletonList() returns the object as an immutable List. This is an easy way to convert a single object into a list. This was added by Java 2.0.
a) unmodifiableCollection() returns a collection that cannot be modified
b) unmodifiableCollection() method is available only for List and Set
c) unmodifiableCollection() is defined in Collection class
d) none of the mentioned
Clarification: unmodifiableCollection() is available for al collections, Set, Map, List etc.
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();
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
b) 1 5 8 2
c) 2
d) 2 1 8 5
Clarification: None.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
2 8 5 1
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);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
b) 1 5 8 2
c) 2
d) 2 1 8 5
Clarification: Collections.reverse(list) reverses the given list, the list was 2->8->5->1 after reversing it became 1->5->8->2.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
1 5 8 2