`
miraclerz
  • 浏览: 97249 次
社区版块
存档分类
最新评论

SCJP真题22

    博客分类:
  • SCJP
阅读更多

QUESTION 106

Given:

 

What is the appropriated definition of the hashCode method in class Person? 

A. return super.hashCode();

B. return name.hashCode() + age * 7;

C. return name.hashCode() + comment.hashCode() / 2;

D. return name.hashCode() + comment.hashCode() / 2 - age * 3;

 

 

Answer: ( B )

两个equals的对象,hashCode()应该相等,equals中是判断agename相等,所以hashCode也用agename计算

 

QUESTION 107

Given:

 

Which statement is true? 

A. The equals method does NOT properly override the Object.equals method.

B. Compilation fails because the private attribute p.name cannot be accessed in line 5.

C. To work correctly with hash-based data structures, this class must also implement the hashCode method.

D. When adding Person objects to java.util. Set collection, the equals method in line 4 will prevent duplicates.

 

Answer: ( A )

A选项的叙述正确。

Object.equals()方法的签名是 public  boolean  equals(Object  obj){}

B选项错误。因为类自己可以通过本类对象名来访问自己的private属性。

C 选项错误。因为Person类没有覆写父类Object类的equals()方法,所以不需要覆写父类Object类的hashCode()也能在基于哈希码的数据结构中正确使用。

根据Sun官方的规范,一个类的对象满足如下的条件便可以正确地用于基于哈希码的数据结构:

l  equals()方法判定为相同的两个对象,用hashCode也必须判定为相同

l  equals()方法判定为不同的两个对象,用hashCode的判定结果可以为不同也可以为相同,但是hashCode也能判断为不同的话可以提高此数据结构的工作性能。

D选项错误。第四行定义方法并没有覆盖从父类Object类继承来的equals方法,而是重载了一个方法名字同为equals但是参数列表不同的equals()方法。Set集合通过调用该类对象的对Object父类的equals方法的覆盖版本来判断重复与否,所以在Set集合中无法避免该类对象的重复。例如:调用构造器创建两个name属性相同的Person对象,业务逻辑上是重复对象但是却都能加入到Set集合中。

 

 

QUESTION 108

Given:

 

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 )

TreeSet可自动排序,SortedSet是接口,不能实例化,TreeSetSortedSet类的唯一实现类。使用TreeSet的迭代器可以保证按照排序顺序来遍历TreeSet

 

QUESTION 109

Given:

 

What, inserted at line 39, will sort the keys in the props HashMap? 

A. Array.sort(s);

B. s = new TreeSet(s);

C. Collections.sort(s);

D. s =new SortedSet(s);  

 

 

Answer: ( B )

TreeSet(Collection<? extends E> c)构造函数是一个浅拷贝构造函数,构造出来的TreeSet集合与作为参数的集合存放着相同对象元素的引用值(地址值)。它构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。插入该 set 的所有元素都必须实现 Comparable 接口。另外,所有这些元素都必须是可互相比较的:对于 set 中的任意两个元素 e1 e2,执行 e1.compareTo(e2) 都不得抛出 ClassCastException

 

 

 

QUESTION 110

Place code into the class so that it compiles and generates the output answer=42. Note: Code options may be used more than once.

 

Answer: (  )

public class Gen<T>{

        private T object;

        public Gen (T object){

                this.object = object;

}

public T getObject(){

return object;

}

}

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics