SCJP : Collections and Generics Mock Exam Practice Questions
Questions no -1
What is the output for the below code ?
public class NameBean {
private String str;
NameBean(String str ){
this.str = str;
}
public String toString() {
return str;
}
}
import java.util.HashSet;
public class CollClient {
public static void main(String ... sss) {
HashSet myMap = new HashSet();
String s1 = new String("das");
String s2 = new String("das");
NameBean s3 = new NameBean("abcdef");
NameBean s4 = new NameBean("abcdef");
myMap.add(s1);
myMap.add(s2);
myMap.add(s3);
myMap.add(s4);
System.out.println(myMap);
}
}
options
A)das abcdef abcdef
B)das das abcdef abcdef
C)das abcdef
D)abcdef abcdef
Correct answer is : A
Explanations : Need to implement 'equals' and 'hashCode' methods to get unique Set for user defind objects(NameBean).
String object internally implements 'equals' and 'hashCode' methods therefore Set only stored one value.
Questions no -2
Synchronized resizable-array implementation of the List interface is _____________?
options
A)Vector
B)ArrayList
C)Hashtable
D)HashMap
Correct answer is : A
Explanations : Vector implements List, RandomAccess - Synchronized resizable-array implementation of the List interface with additional "legacy methods."
Questions no -3
What is the output for the below code ?
public class Test {
public static void main(String argv[]){
ArrayList list = new ArrayList();
ArrayList listStr = list;
ArrayList listBuf = list;
listStr.add(0, "Hello");
StringBuffer buff = listBuf.get(0);
System.out.println(buff.toString());
}
}
options
A)Hello
B)Compile error
C)java.lang.ClassCastException
D)null
Correct answer is : C
Explanations : java.lang.String cannot be cast to java.lang.StringBuffer at the code StringBuffer buff = listBuf.get(0);
So thows java.lang.ClassCastException.
Questions no -4
What is the output for the below code ?
import java.util.LinkedList;
import java.util.Queue;
public class Test {
public static void main(String... args) {
Queue q = new LinkedList();
q.add("newyork");
q.add("ca");
q.add("texas");
show(q);
}
public static void show(Queue q) {
q.add(new Integer(11));
while (!q.isEmpty ( ) )
System.out.print(q.poll() + " ");
}
}
options
A)Compile error : Integer can't add
B)newyork ca texas 11
C)newyork ca texas
D)newyork ca
Correct answer is : B
Explanations : q was originally declared as Queue<String>, But in show() method it is passed as an untyped Queue. nothing in the compiler or JVM prevents us from adding an Integer after that.
If the show method signature is public static void show(Queue<String> q) than you can't add Integer, Only String allowed. But public static void show(Queue q) is untyped Queue so you can add Integer.
poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
|