每天几条java题(1)

阿里电面虽然java基本能够回答出来,但是后来的java竞赛里面发现居然还有些题要google和百度,被打击了,为了下次能够在阿里面试里面翻身,为了帮小师妹打比赛,好好学java。每天做一下scjp或者ocjp题目,顺便记一下api。环境:Jdk1.7u51

先是scjp 1.5,然后就是310-055题库,最后1Z0-851

 

Question: 1
Given:
11. public class Person {
12. private String name, comment;
13. private int age;
14. public Person(String n, int a, String c) {
15. name = n; age = a; comment = c;
16. }
17. public boolean equals(Object o) {
18. if (! (o instanceof Person)) return false;
19, Person p = (Person)o;
20. return age == p.age && name.equals(p.name);
21. }
22. }

What is the appropriate 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

 

hashCode

public int hashCode()

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

返回一个对象的hash code值。这个方法被用在hash tables中,例如HashMap

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • 在一个执行的java程序里面,同一个对象多次调用hashcode,那么这个方法就会固定地返回一个相同的整数值,前提是将对象进行 equals 比较时所用的信息没有被修改。这个整数值在不同的java程序执行中不一定相同。
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • 如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
  • 如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么对这两个对象中的任一对象上调用 hashCode 方法不 要求一定生成不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

实际上,由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。一般是通过将该对象的内部地址转换成一个整数来实现的

Returns:

a hash code value for this object.

See Also:

equals(java.lang.Object), System.identityHashCode(java.lang.Object)

题目分析:

很明显hashcodeequals有关,这里重写了equals,解读这个equals()发现是根据年龄和名字来判断是否相同的。只要名字和年龄相同了,hashcode返回整数就相同。

首先是CD:有个comment在里面,不符合上equals()的条件,不行。

然后AB:根据“由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。”,A对不同对象产生相同的hashCode返回值。所以A错。

答案B

 

 


Question 2:
Given:
34. HashMap props = new HashMap();
35. props.put("key45", "some value");
36. props.put("key12", "some other value");
37. props.put("key39", "yet another value");
38. Set s = props.keySet();
39. // insert code here
What, inserted at line 39, will sort the keys in the props HashMap?
A. Arrays.sort(s);
B. s = new TreeSet(s);
C. Collections.sort(s);
D. s = new SortedSet(s);

Answer: B

题目解析:

A:在java.utils.Arrays 里面的sort()方法都是用数组作为参数之一,没有set做参数的,排除A

BDtreeset是实现sortedset接口的

TreeSet中有一个构造方法对collection子类进行排序

public TreeSet(Collection<? extends E> c)

构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。插入该 set 的所有元素都必须实现 Comparable 接口。另外,所有这些元素都必须是可互相比较的:对于 set 中的任意两个元素 e1 和 e2,执行 e1.compareTo(e2) 都不得抛出 ClassCastException。

参数:

c - 一个 collection,其元素将组成新的 set

抛出:

ClassCastException - 如果 c 中的元素不是 Comparable,或者是不可相互比较的

NullPointerException - 如果指定 collection 为 null

B正确,D错误

C:

public static <T extends Comparable<? super T>> void sort(List<T> list)

根据元素的自然顺序 对指定列表按升序进行排序。列表中的所有元素都必须实现 Comparable 接口。此外,列表中的所有元素都必须是可相互比较的(也就是说,对于列表中的任何 e1 和 e2 元素,e1.compareTo(e2) 不得抛出 ClassCastException)。

此排序方法具有稳定性:不会因调用 sort 方法而对相等的元素进行重新排序。

指定列表必须是可修改的,但不必是大小可调整的。

该排序算法是一个经过修改的合并排序算法(其中,如果低子列表中的最高元素小于高子列表中的最低元素,则忽略合并)。此算法提供可保证的 n log(n) 性能。 此实现将指定列表转储到一个数组中,并对数组进行排序,在重置数组中相应位置处每个元素的列表上进行迭代。这避免了由于试图原地对链接列表进行排序而产生的 n2 log(n) 性能。

参数:

list - 要排序的列表。

抛出:

ClassCastException - 如果列表包含不可相互比较 的元素(例如,字符串和整数)。

UnsupportedOperationException - 如果指定列表的列表迭代器不支持 set 操作。

另请参见:

Comparable

 


public static <T> void sort(List<T> list,Comparator<? super T> c)

根据指定比较器产生的顺序对指定列表进行排序。此列表内的所有元素都必须可使用指定比较器相互比较(也就是说,对于列表中的任意 e1 和e2 元素,c.compare(e1, e2) 不得抛出 ClassCastException)。

此排序被保证是稳定的:不会因调用 sort 而对相等的元素进行重新排序。

排序算法是一个经过修改的合并排序算法(其中,如果低子列表中的最高元素小于高子列表中的最低元素,则忽略合并)。此算法提供可保证的 n log(n) 性能。 指定列表必须是可修改的,但不必是可大小调整的。此实现将指定列表转储到一个数组中,并对数组进行排序,在重置数组中相应位置每个元素的列表上进行迭代。这避免了由于试图原地对链接列表进行排序而产生的 n2 log(n) 性能。

参数:

list - 要排序的列表。

c - 确定列表顺序的比较器。null 值指示应该使用元素的自然顺序。

抛出:

ClassCastException - 如果列表中包含不可使用指定比较器相互比较 的元素。

UnsupportedOperationException - 如果指定列表的列表迭代器不支持 set 操作。

另请参见:

Comparator

 

 


Question 3:
Which statement is true about the set variable on line 12?
import java.util.*;
public class TestSet{
enum Example { ONE, TWO, THREE }
public static void main(String args[])
{
Collection coll=new ArrayList();
coll.add(Example.THREE);
coll.add(Example.THREE);
coll.add(Example.THREE);
coll.add(Example.TWO);
coll.add(Example.TWO);
coll.add(Example.ONE);
Set set=new HashSet(coll);
}
}
A. The set variable contains all six elements from the coll collection, and the order is guaranteed to be preserved.
B. The set variable contains only three elements from the coll collection, and the order is guaranteed to be preserved.
C. The set variable contains all six elements from the coll collection, but the order is NOT guaranteed to be preserved.
D. The set variable contains only three elements from the coll collection, but the order is NOT guaranteed to be preserved.

Answer: D

 

问题解释:

这题就没需要查doc了,首先hashset不允许对象重复,则只能有3个元素了,排除AC

由于hashset中元素顺序跟插入顺序是无关的,所以没有必要保证按顺序插入。就只有D了。

 

 


Question 4:
Given:
23. Object [] myObjects = {
24. new Integer(12),
25. new String("foo"),
26. new Integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for(int i=0; i<myObjects.length; i++) {
31. System.out.print(myObjects[i].toString());
32. System.out.print(" ");
33. }
What is the result?
A. Compilation fails due to an error in line 23.
B. Compilation fails due to an error in line 29.
C. A ClassCastException occurs in line 29.
D. A ClassCastException occurs in line 31.
E. The value of all four objects prints in natural order.

Answer: C

 

问题解释:

先来看看Array.sort()

Sort   jdk1.7

public static void sort(Object[] a)

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

根据元素的自然顺序对指定对象数组按升序进行排序。数组中的所有元素都必须实现 Comparable 接口。此外,数组中的所有元素都必须是可相互比较的(也就是说,对于数组中的任何 e1 和 e2 元素而言,e1.compareTo(e2) 不得抛出 ClassCastException)。

保证此排序是稳定的:不会因调用 sort 方法而对相等的元素进行重新排序。

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

The implementation was adapted from Tim Peters's list sort for Python ( TimSort). It uses techiques from Peter McIlroy's "Optimistic Sorting and Information Theoretic Complexity", in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

Parameters:

a - the array to be sorted

Throws:

ClassCastException - if the array contains elements that are not mutually comparable (for example, strings and integers)

IllegalArgumentException - (optional) if the natural ordering of the array elements is found to violate the Comparable contract

由上面翻译出来可以知道,要能够转换的!所以,stringinteger是不能相互转换。

这个要看一下Array.sort()的源码了,object[]参的方法是怎样判断跟进行相互转换的,又涉及到compare()。而且Array.sort()是进行一个优化过的归并排序,不是很有意思嘛?

Integerstring还是有相互转换的:String str = Integer.toString(i);

 

 


Question 5:
Given:
1. public class Person {
2. private String name;
3. public Person(String name) { this.name = name; }
4. public boolean equals(Person p) {
5. return p.name.equals(this.name);
6. }
7. }
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 a java.util.Set collection, the equals method in line 4 will prevent duplicates.

Answer: A

 

题解:

equals方法的参数列表与父类不同,父类的参数是Object类型,因此此equals方法不是重写而是重载继承自父类的方法。

B,写过java地球人都知道错的。

Cobjecthashcode()就好

D,是hashCode()进行,语法上hashcode()equals()无关。

通常情况(常规协定)

equals如果是true,必须保证hashcode相同equals如果是false,必须保证hashcode不同。

 

posted @ 2014-04-14 21:40  Fresher_Z  阅读(787)  评论(2编辑  收藏  举报