场景:
在练习
错题
错题1描述:
public class Demo {
public static void main(String[] args) {
Collection<?>[] collections =
{new HashSet<String>(), new ArrayList<String>(), new HashMap<String, String>().values()};
Super subToSuper = new Sub();
for(Collection<?> collection: collections) {
System.out.println(subToSuper.getType(collection));
}
}
abstract static class Super {
public static String getType(Collection<?> collection) {
return “Super:collection”;
}
public static String getType(List<?> list) {
return “Super:list”;
}
public String getType(ArrayList<?> list) {
return “Super:arrayList”;
}
public static String getType(Set<?> set) {
return “Super:set”;
}
public String getType(HashSet<?> set) {
return “Super:hashSet”;
}
}
static class Sub extends Super {
public static String getType(Collection<?> collection) {
return "Sub"; }
}
}
A. Sub:collection
Sub:collection
Sub:collection
B. Sub:hashSet
Sub:arrayList
Sub:collection
C.Super:collection
Super:collection
Super:collection
D.Super:hashSet
Super:arrayList
Super:collection
原因分析:
复习一下多态
多态对象只能够调用父类的方法
如果子类重写了父类的方法,则会调用子类的方法
子类和父类都是静态,子类就不能覆盖父类的,所有调用父类的
这道题考察重载 跟多态与静态
这里是静态方法,子类不能重写把 Sub的排除 A B
然后new HashSet(), new ArrayList(), new HashMap<String, String>().values()
都是Collection的子类,程序会顺序执行
答案选C
错题2描述:
以下输出结果为false的是:
Integer i01=59;
int i02=59;
Integer i03=Integer.valueOf(59);
Integer i04=new Integer(59);
A. System.out.println(i01==i02);
B. System.out.println(i01==i03);
C. System.out.println(i03==i04);
D. System.out.println(i02==i04);
原因分析:
①无论如何,Integer与new Integer不会相等。不会经历拆箱过程,
②两个都是非new出来的Integer,如果数在-128到127之间,则是true,否则为false
java在编译Integer i2 = 128的时候,被翻译成-> Integer i2 = Integer.valueOf(128);而valueOf()函数会对-128到127之间的数进行缓存
③两个都是new出来的,都为false
④int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比
答案:C
错题3描述:
下面论述正确的是()?
A. 如果两个对象的hashcode相同,那么它们作为同一个HashMap的key时,必然返回同样的值
B. 如果a,b的hashcode相同,那么a.equals(b)必须返回true
C. 对于一个类,其所有对象的hashcode必须不同
D. 如果a.equals(b)返回true,那么a,b两个对象的hashcode必须相同
原因分析:
1.equals()相等的两个对象他们的hashCode()肯定相等,也就是用equals()对比是绝对可靠的
。
2.hashCode()相等的两个对象他们的equal()不一定相等,也就是hashCode()不是绝对可靠的。
答案:D