Arrays comparation in java [duplicate] - java

int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?

Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case

The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 are not the same object.
In the case of m, the same idea holds. Object#toString() prints out an object identifier. In my case when I printed them out and checked them, the result was
nir1 = [I#3e25a5
nir2 = [I#19821f
Which are, of course, not the same.
CoolBeans is correct; use the static Arrays.equals() method to compare them.

Use Arrays.equals instead of array1.equals(array2). Arrays.equals(array1, array2) will check the content of the two arrays and the later will check the reference. array1.equals(array2) simply means array1 == array2 which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}

boolean t = Arrays.equals(nir1,nir2)

I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
Arrays.toString(nir1);
and
Arrays.deepToString(nir1);
for complex arrays.
Also, for equality:
Arrays.equals(nir1,nir2);

Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this

Related

I didn't understand why I am getting false, instead of getting true, please look into the code and help me [duplicate]

int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 are not the same object.
In the case of m, the same idea holds. Object#toString() prints out an object identifier. In my case when I printed them out and checked them, the result was
nir1 = [I#3e25a5
nir2 = [I#19821f
Which are, of course, not the same.
CoolBeans is correct; use the static Arrays.equals() method to compare them.
Use Arrays.equals instead of array1.equals(array2). Arrays.equals(array1, array2) will check the content of the two arrays and the later will check the reference. array1.equals(array2) simply means array1 == array2 which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}
boolean t = Arrays.equals(nir1,nir2)
I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
Arrays.toString(nir1);
and
Arrays.deepToString(nir1);
for complex arrays.
Also, for equality:
Arrays.equals(nir1,nir2);
Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this

Array.equal() giving wrong output

To my understanding, the following code should print true, since both elements are equal.
From java docs Array.get() will return:
Returns the value of the indexed component in the specified array
object. The value is automatically wrapped in an object if it has a
primitive type.
However, when I run the following code it is printing
false:
public class Test1 {
static boolean equalTest(Object array1, Object array2) {
return Array.get(array1, 0).equals(Array.get(array2, 0));
}
public static void main(String[] args) {
int[] a = new int[1];
byte[] b = new byte[1];
a[0] = 3;
b[0] = 3;
System.out.println(equalTest(a, b));
}
}
My question is isn't classes implementing Number are or should be directly comparable to one another.
This has nothing to do with arrays really. Your comparison is equivalent to:
Object x = Integer.valueOf(3);
Object y = Byte.valueOf((byte) 3);
boolean equal = x.equals(y);
That's never going to return true.
Even though your original arrays are of the primitive types, Array.get returns Object, so you're getting the boxed types - and comparing values of those different types.
According to the documentation of Array.get(Object array,int index) method, the value returned is automatically wrapped in an object if it has a primitive type. So, if you add the following lines:
System.out.println(Array.get(array1, 0).getClass());
System.out.println(Array.get(array2, 0).getClass());
you will see the output is
class java.lang.Integer
class java.lang.Byte
The equals method of Integer class first of all checks if the object it is being compared to is also an instance of Integer, if not , then no further checks are required, they are not equal.
That's the reason you see the output is false as the objects being compared for equality are Integer and Byte.
The Array.get invocations return Integer and Byte object instances. These are not equal according to Integer.equals because the class type differs.
The problem is that the Array.get() method returns an object, so for int it'll return Integer, and for byte, it will return Byte. So .equals() method will return false because it first sees whether the type is the same, and then compares the values.
The array data types don't match. One is int and the other is byte. Since they're being passed to the function as Objects, they'll end up being Integer and Byte. So in order to compare them properly, you need to type-cast them to the same type. Something like:
static boolean equalTest(Object array1, Object array2) {
int int1 = (int) Array.get(array1, 0);
int int2 = (int) Array.get(array2, 0);
return int1.equals(int2);
// OR return int1 == int2;
}
If you look at the JavaDoc for Array.get you'll see:
The value is automatically wrapped in an object if it has a primitive
type.
So your bytes become Bytes and your ints become Integers.
That means the function you're calling is Integer.equals(Object)
This is implemented like so:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
You're not passing it an Integer, you're passing it a Byte so that's why it returns false.

Java-trouble with not equal to

I am trying to solve a question. But the program control is going into the if statement even when both the numbers I check are the same which is not supposed to happen. What is the reason?
static int lonelyinteger(int[] a) {
Integer[] b=new Integer[a.length];
for(int i=0;i<a.length;i++){
b[i]=new Integer(a[i]);
}
int val=0;
Arrays.sort(b);
boolean flag=false;
for(int i=0;i<a.length-2;i+=2)
if (b[i]!=b[i+1]){
val=b[i];
flag=true;
break;
}
if(flag==true)
return val;
else
return b[a.length-1];
You are using != on Integer objects. This will only work with integer values between -128 and 127 (reference) because these are cached by the JVM. But it won't work for larger/smaller values. Instead use .equals
if (!b[i].equals(b[i+1])){
val=b[i];
flag=true;
break;
}
As correctly pointed out by Jesper in the comments, the cache used for Integer objects by the JVM is not used when you force the JVM to create new Integer objects through the explicit call of the constructor as in new Integer(value). Calling the constructor will create new Integer instances instead of returning the cached Integer instances, which means that != and == which check whether the two objects are the same instance will always think the instances are different.
1) Do not use new Integer() use Integer.valueOf() instead.
2) Use Object.equals() when comparing objects.
if (b[i]!=b[i+1]) {
...
}
should be
if (!b[i].equals(b[i+1])) {
...
}

Comparing int value in java?

I have an issue when i compare folderInfoData.getFolderInfoRecord().getInfoCode() and map.get("infoCode") below code .Both give value=2 But my issue is that its not enter inside if condition.
Here's example :
if (folderInfoData.getFolderInfoRecord().getInfoCode().equals(map.get("infoCode"))) {
showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS"));
return;
}
Before i googled its not effective for me:Comparing Integer objects vs int
Can anyone tell mehow can resolve this issue ?
Thanks
In the comments you state that the map was declared Map<String, Object>. That's probably the problem.
When you call map.get("infoCode") you're getting back an Object.
If:
that Object is actually an instance of Integer
folderInfoData.getFolderInfoRecord().getInfoCode() is returning an Integer
both Integers contain the same value
Then this:
if (folderInfoData.getFolderInfoRecord().getInfoCode()
.equals(map.get("infoCode"))) {
Would evaluate to true.
So either they are two Integers but don't both contain the same value, or they are different types of objects and are not equal. (Or, "infoCode" doesn't exist in the map and it's returning null)
If you want to use .equals(), the best way is by make sure it always return Integer instead of int
int num1 = Integer.parseInt(folderInfoData.getFolderInfoRecord().getInfoCode());
int num2 = Integer.parseInt(map.get("infoCode"));
if (new Integer(num1).equals(new Integer(num2))) {
showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS"));
return;
}
You have to check whether both are Integer instances having the correct value so, that is passes equality test. The test will definitely get pass when both Integer values are same. Please debug your code and find out. There is no use in changing it to ==.
if it return String
if (Integer.parseInt(folderInfoData.getFolderInfoRecord().getInfoCode()) == Integer.parseInt(map.get("infoCode"))) {
showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS"));
return;
}
else
if (folderInfoData.getFolderInfoRecord().getInfoCode() == map.get("infoCode")) {
showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS"));
return;
}
try this is also
if (folderInfoData.getFolderInfoRecord().getInfoCode().toString.trim().equals(map.get("infoCode").toString().trim())) {
showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS"));
return;
}
Seems that you are comparing int with an Integer. Java will convert an Integer into an int automatically
So
int a = 2;
Integer b = a;
System.out.println(a == b);
becomes
int a = 2;
Integer b = new Integer(a);
System.out.println(a == b.valueOf());
So if you want to use equals, See Rafa El answer. else you can use ==.

What is an efficient way to compare StringBuilder objects

Well I have two StringBuilder objects, I need to compare them in Java.
One way I know I can do is
sb1.toString().equals(sb2.toString());
but that means I am creating two String objects, is there any better way to compare StringBuilder objects. Probably something where you do not need to create additional objects?
As you apparently already know, StringBuilder inherits equals() from java.lang.Object, and as such StringBuilder.equals() returns true only when passed the same object as an argument. It does not compare the contents of two StringBuilders!
If you look at the source, you'll conclude that the most efficient comparison (that didn't involve creating any new objects) would be to compare .length() return values, and then if they're the same, compare the return values of charAt(i) for each character.
Since Java 11, StringBuilder implements Comparable, so you can use a compareTo method for the equality test:
System.out.println(sb1.compareTo(sb2) == 0);
Two StringBuilder objects are never equal. Use .toString() to get the string representation for both the objects and then use .equals() to compare the objects. This way equals() method from the String class gets invoked that compares the string value of the objects instead of comparing the memory location.
StringBuilder a= new StringBuilder("HELLO JAVA");
StringBuilder b= new StringBuilder("HELLO JAVA");
if (a.toString().equals(b.toString())){
System.out.println("Objects are equal");
}
A solution without new allocations would be to compare first at length, and if it differs, then char by char. This is more efficient and faster than performing a compare via a toString() on the StringBuilder call, which would allocate a new string.
The next snipped assumes both parameters aren't null neither the same object instance:
public boolean compare(final StringBuilder left, final StringBuilder right) {
final int length = left.length();
if (length != right.length())
return false;
for (int index = 0; index < length; index++) {
if (left.charAt(index) != right.charAt(index))
return false;
}
return true;
}

Categories