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?
Regarding question 1: arrays inherit the default implementation of
equals()fromObject, which returnstrueonly if the two objects are identical. You can test arrays for equality of contents using: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.