Some questions about arrays

I have 2 questions about arrays in Java, hope you can save 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 does it return 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 the duplication:

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

now it returns 2, which is correct.

I don’t know how binary search in an array deals with duplication, which leads to -2?

+5
source share
6 answers

As for question 1: arrays inherit the default implementation equals()from Object, which returns trueonly if both objects are identical. You can check arrays for equality of content using:

Arrays.equals(intArray1, intArray2);

2: , ( ) . , , .

+7

, binarySearch , . javadoc:

int , . ( , ) . , undefined. , , .

equals false, : , equals , , , . Arrays.equals , .

+5

Array Java equals(). , Arrays.equals():

Arrays.equals(intArray1, intArray2);

:

Arrays.sort(intArray1);
+4

1:

equals (.. ), . , equals false, .

+2

№ 1: equals() , . , equals() . Arrays.equals(int [] a, int [] a2). :

true, . , . e1 e2 equal if (e1 == null? e2 == null: e1.equals(e2)). , , . , , .

№ 2: Javadoc binarySearch (int [] a, int key):

int , . ( sort (int []) . , undefined. , , .

, , , , .

+1

- , sorted array, .

- -, Arrays.equals():

Arrays.equals(intArray1, intArray2);

0

All Articles