Question: 6
Given:1. import java.util.*;2. public class Old { 3. public static Object get0(List list) { 4. return list.get(0);5. }6. }Which three will compile successfully? (Choose three.)A. Object o = Old.get0(new LinkedList());B. Object o = Old.get0(new LinkedList<?>());C. String s = Old.get0(new LinkedList<String>());D. Object o = Old.get0(new LinkedList<Object>());E. String s = (String)Old.get0(new LinkedList<String>());Answer: A, D, E
题目分析:
C没有强制转换。
?是不确定类的时候用,但是不确定是只在子类型父类型里面应用,例如list<? Extends X>,那么这里就可以是X或者其子类,list的泛型实际类型就是初始化时候的那个类型。
范例代码(来源于网上)
import java.util.ArrayList;
import java.util.List;
class Parent {
// your code
}
class Child extends Parent {
// your code
}
public class test {
// 这里更改一下,利用问号解决问题
public static void doTest(List <? extends Parent > list) {
}
public static void main(String[] args) {
List < Parent > parentList = new ArrayList < Parent > ();
List < Child > childList = new ArrayList < Child > ();
doTest(parentList);
// 注意这里编译正确
doTest(childList); }
}
Question: 7Given:1. import java.util.*;2. public class Example { 3. public static void main(String[] args) { 4. // insert code here5. set.add(new Integer(2));6. set.add(new Integer(1));7. System.out.println(set);8. }9. }Which code, inserted at line 4, guarantees that this program will output [1, 2]?A. Set set = new TreeSet();B. Set set = new HashSet();C. Set set = new SortedSet();D. List set = new SortedList();E. Set set = new LinkedHashSet();Answer: A
题解:
首先不用想A肯定是对的,sortedset,之前也说过,接口。还有java是没有sortedlist的,你要用collection.sort来排序,为啥这样设计??Stackoverflow上面有人问过。
Linkedhashset跟插入顺序有关,错。
至于Hashset,我也不懂,但是把代码写过去,hashset是输出[1,2]的。
个人认为答案为A,B,特意在stackoverflow上面找到这么一段东西:
A hashcode is an integer value that represents the state of the object upon which it was called. That is why an Integer that is set to 1 will return a hashcode of "1" because an Integer's hashcode and its value are the same thing. A character's hashcode is equal to it's ASCII character code. If you write a custom type you are responsible for creating a good hashCode implementation that will best represent the state of the current instance.
然后引申出一个新的问题:hashset是真的无序的么?至少,对于Integer来说它不是无序的。