Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about Arrays [closed]

Tags:

java

arrays

I have 2 questions about Arrays in Java, hope you can spare your time to help me.

Question 1:

int[] intArray1 = { 1, 4, 2, 5, 6, 7, 2 };  
int[] intArray2 = { 1, 4, 2, 5, 6, 7, 2 };

intArray1.equals(intArray2);

But it returns false?

Question 2:

I run this code:

int[] intArray1 = { 1, 4, 2, 5, 6, 7, 2 };  //2 is duplicated
Arrays.binarySearch(intArray1,2);

and it returns -2.

BUT when I remove duplication:

int[] intArray3 = { 1, 4, 2, 5, 6, 7}; // nothing is duplicated
Arrays.binarySearch(intArray1,2);

now it returns 2, which is the right one.

I don't know how binary Search in Array deals with duplication which lead to -2?

like image 346
Huy Than Avatar asked Sep 30 '12 07:09

Huy Than


People also ask

How useful is array in solving programming problems?

Arrays are used when there is a need to use many variables of the same type. It can be defined as a sequence of objects which are of the same data type. It is used to store a collection of data, and it is more useful to think of an array as a collection of variables of the same type.


1 Answers

Regarding question 1: arrays inherit the default implementation of equals() from Object, which returns true only if the two objects are identical. You can test arrays for equality of contents using:

Arrays.equals(intArray1, intArray2);

Regarding question 2: Unless the array is sorted, binary search returns unpredictable (and often wrong) results. That it happens to work on a specific unsorted array is a coincidence.

like image 190
Ted Hopp Avatar answered Sep 27 '22 17:09

Ted Hopp