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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With