Java-trouble with not equal to - java

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])) {
...
}

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

Arrays comparation in java [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

Which is better in use between int and Integer to determine the values?

I would like to know when I am checking for integers input, should I use int or Integer for checking?
Below is some mock-up codes:
This one uses int:
public State editState (int stateID, String stateCode) {
if (stateID == 0) {
throw new Exception("State id not set.");
}
...
State s = new State();
...
return s;
}
This one uses Integer:
public State editState (Integer stateID, String stateCode) {
if (stateID == null) {
throw new Exception("State id not set.");
}
...
State s = new State();
...
return s;
}
Which approach is better in use?
when you will invoke editState(..,..) and stateId is not set then two cases arise-
1)editState(0,"some code");
2)editState(null,"some code");
It depends upon the criteria you set for the unacceptance of stateID.
If you set criteria for unacceptance as null then you will have to use 'Integer'
and if 0 then you can use both 'Integer' and 'int' ...
so it depends upon the criteria you set at the invoking side..
And i think Integer (wrapper class ) is better due to excellent auto boxing ,unboxing features
as well as various methods provided to you for manipulations if required...
There is no much difference performance wise or functionality wise. Both would be almost equal. It depends more on how the input is in the method invoking the editState(...) method. If the invoking method has primitive type int or wrapper Integer, corresponding editState(...) is better to use.
Also, if the invoking method has the possibility of different numeric types (byte, short etc.) that fits into int, then first one is preferred. Similarly if it has object that can be autoboxed to Integer, then second one is preferred.
Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:
Integer i = new Integer(6);
You could call some method on i:
String s = i.toString(); //sets s the string representation of i
Whereas with an int:
int i = 6;
You cannot call any methods on it, because it is simply a primitive. So:
String s = i.toString(); //will not work!!!
would produce an error, because int is not an object.
I think if you have not any requirement to use such operation then go with int instead of Integer and you can also avoid a unnecessary Java object creation.

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 ==.

compacting an array in java by removing certain objects

For my computer science class we are supposed to take an array of objects {A,C,D,C,C,F,C,G} and sets all elements of a certain object to null. Object is C: {A,null,D,null,null,F,null,G}
Then we are supposed to move all the remaining object to the front of the array {A,D,F,G,null,null,null,null}...
So far I tried this but I cant find the problem with my method:
public static void compact (Object[] vec, Object item) {
int a=0;
for(int i=0; i < vec.length; i++)
{
if(vec[i]==item)
{
vec[i] = null;
}
else
{
vec[i]=vec[a];
a++;
}
}
for(int b=a; b < vec.length-(a-1); b++)
{
vec[b]=null;
}
}
Help please?
if(vec[i]==item)
Never use == for comparing objects, use equals() (and, when you define a new class, take care in implementing equals() and hashCode() in a practical way)
Of course there may be other problems, but since you are not even telling what it is failing I won't care much.
I think you want equals() rather than == unless testing for null. You are using an object.

Categories