Several java questions every day (1)

Source: Internet
Author: User

First

 

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.

Returns the hash code of an object.

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.
  • In a 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.
  • If
  • 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 shocould be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
  • If

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 .)

In fact

Returns:

A hash code value for this object.

See Also:

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

Question Analysis:

Obviously, hashcode

First, C

Then ",

Answer

 

 


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

Question Analysis:

A

BD

There is a constructor in TreeSet that sorts collection subclasses.

Public TreeSet (Collection <? Extends E> c)

Construct a new TreeSet containing the specified collection elements, which are sorted in the natural order of the elements. All elements inserted into the set must implement the Comparable interface. In addition, all these elements must be comparable: For any two elements e1 and e2 in the set, executing e1.compareTo (e2) will not throw ClassCastException.

Parameters:

C-a collection, whose elements are grouped into new sets

Throw:

ClassCastException-if the elements in c are not Comparable or cannot be compared with each other

NullPointerException-if the specified collection is null

B

C:

Public static <T extends Comparable <? Super T> void sort (List <T> list)

Sort the specified list in ascending order based on the natural order of the elements. All elements in the list must implement the Comparable interface. In addition, all elements in the list must be comparable to each other (that is, for any e1 and e2 elements in the list, e1.compareTo (e2) cannot throw ClassCastException ).

This sorting method is stable: equal elements are not re-ordered because the sort method is called.

The specified list must be changeable, but not the size.

This sort algorithm is a modified merge sort algorithm. (If the highest element in the lower sublist is smaller than the lowest element in the upper sublist, merge is ignored ). This algorithm provides guaranteed n log (n) performance. This method dumps the specified list to an array, sorts the array, and iterates on the list of each element at the corresponding position in the reset array. This avoids the n2 log (n) performance caused by an attempt to sort the link list in the same place.

Parameters:

List-the list to be sorted.

Throw:

ClassCastException-if the list contains elements that cannot be compared with each other (for example, strings and integers ).

UnsupportedOperationException-if the list iterator of the specified list does not support the set operation.

For more information, see:

Comparable

 


Public static <T> void sort (List <T> list, Comparator <? Super T> c)

Sorts the specified list based on the Generation sequence of the specified comparator. All elements in this list must be compared with each other using the specified comparator (that is, for any e1 and e2 elements in the list, c. compare (e1, e2) cannot throw ClassCastException ).

This sorting is ensured to be stable: equal elements are not re-ordered by calling sort.

The merge sort algorithm is a modified merge sort algorithm. (If the highest element in the low sublist is smaller than the lowest element in the high sublist, merge is ignored ). This algorithm provides guaranteed n log (n) performance. The specified list must be changeable, but not large or small. This method dumps the specified list to an array, sorts the array, and iterates on the list of each element at the corresponding position in the reset array. This avoids the n2 log (n) performance caused by an attempt to sort the link list in the same place.

Parameters:

List-the list to be sorted.

C-the comparator that determines the list order. The null value indicates that the natural sequence of elements should be used.

Throw:

ClassCastException-if the list contains elements that cannot be compared with each other using the specified comparator.

UnsupportedOperationException-if the list iterator of the specified list does not support the set operation.

For more information, see:

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

 

Explanation:

No need to check the doc for this question.

Because

 

 


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

 

Explanation:

Let's take a look

Sort jdk1.7

Public static void sort (Object [])

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.

Sort the array of specified objects in ascending order based on the natural order of elements. All elements in the array must be implemented.

This sorting is stable: it is not called

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 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

It can be understood from the translation above. It must be convertible! So,

Let's take a look.

Integer

 

 


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:

 

Question:

Equals

B

C

D

General situation

Equals

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.