Why aren't identical arrays, when passed as strings considered equal? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
1) if I set
int[] set1 = new int[]{1, 2};
int[] set2 = new int[]{1, 2};
how come when I pass them as strings using
System.out.println(Arrays.toString(set1) == Arrays.toString(set2));
it returns false?
2) Is there any way to compare equality of entire arrays without looping through each index of the array?

Strings are Objects, so they should be compared using equals:
System.out.println(Arrays.toString(set1).equals(Arrays.toString(set2))); //prints true
Use Arrays#equals to compare arrays, note that the arrays must have the same length and the items must be equals: == for primitives (int, long ...) and equals for Object references).

== compares string references, not values. Use str1.equals(str2). (more information on this here; it basically compare whether the actual objects are the same, not the string content)
No, naturally if you want to know if each element is the same you'll have to loop through all of them. Arrays#toString does this behind the scenes also (how else would it get a string representation?).
Sidenote: converting an array to a string introduces a lot of unnecessary overhead (string manipulation, etc.). You should probably just loop through and compare elements, or create a helper method (or use a built-in one like Arrays#equals).

Use Arrays.equals to compare arrays and see this for Strings comparisons.

Related

Comparing Integer and int with == [duplicate]

This question already has answers here:
How can I properly compare two Integers in Java?
(10 answers)
Is it safe to compare two `Integer` values with `==` in Java? [duplicate]
(2 answers)
How do I compare two Integers? [duplicate]
(9 answers)
Comparing Integer objects [duplicate]
(5 answers)
Closed 1 year ago.
List<Integer> test = List.of(955, 955);
if (test.get(1) == test.get(0))
...
Above condition results in false
List<Integer> test = List.of(955, 955);
int a = test.get(1);
int b = test.get(0);
if (a == b)
...
The above condition returns true.
Why is that the case? What is the difference between the snippets?
In one case, you're comparing two Integer object references. In the other case, you're comparing two ints. When using the == operator to compare object references, it will return False if they are not the same object, even if they do wrap the same value.
In the first example, you are comparing references. In your example, you have two different objects with different references and the same values.
In the second example, you are using automatic unboxing which creates new integers in stack memory, and integer comparison which works what you expect. Automatic unboxing can produce NullPointerException in case of null.
First Code Snippet:
You are comparing the object reference, meaning the specific object reference that the object is pointing too. In this case you are comparing an Integer which is a wrapper class for int.
Second Code Snippet:
You are comparing the an 'int' to another 'int'.
Example:
Think about it this way: if two people had the name John, in the first scenario we are comparing the people named John, whereas in the second scenario we are comparing the name John only. I hope that helped!

String array vs String split array [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
String s = "Hi Hello Hola";
String[] d = s.split(" ");
System.out.println(d[0] == "Hi"); // prints false
String[] e = { "Hi", "Hello", "Hola" };
System.out.println(e[0] == "Hi"); // prints true
Here we have an array d with the values Hi, Hello, and Hola. We have another array e with the same set of values.
But why does this comparison behaves differently? Why does it print false and then true?
I expected false for both! As we are comparing a string literal value with the string value by using ==.
Why is this difference?
Update Here my question is not about the comparison of String values. I'm aware of the differences between == which compares the references and equals() which compares the content of the string.
From the answers, i understand that in the second case, Hi value is interned and refers to the same object. But in the other case, split creates new values without checking the literal pool. Is it right? Am i missing anything?
The reason beeing is the compiler. At compile time the compiler does notice that the literal Hi exists twice in the code and does intern this string for your specific class.
After compilation both of your interned strings Hi are pointing to the same reference of Hi. That´s the reason why the second print results in true.
The split doesn´t know it´s result and creates new references for the corresponding Strings. That´s the reson why Hi from the split and the literal Hi are not using the same reference.
This is happening because internally when split(Pattern) matches the pattern, and finds the matching char sequences, then it uses String.substring(start,end) for creating a new String object. That is why results returned by split are false. This is code snippet from java.util.regex.Pattern.split(CharSequence input, int limit) class.
String match = input.subSequence(index, m.start()).toString();
Here the input is instance of the String class, which is passed to the Pattern.split(CharSequence, int) method.
Reference: Pattern
Trying to use '==' on strings is very unpredictable. The first time you type in "Hi" as a literal, it is saved into memory. When you then assign it into the array 'e', it uses that same saved literal for storing it in the array. When you then check to see if they are equal, it resolves as true.
I highly recommend not using '==' and use one of the many methods that are provided in Java.
System.out.println("Hi".equals(d[0]));
System.out.println("Hi".equals(e[0]));
or...
System.out.println(("Hi".compareTo(d[0]) == 0));
System.out.println(("Hi".compareTo(e[0]) == 0));

Why does this md5 not match [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i recently started to do some encryption with Apache DigestUtils. I simply want to use md5 hashes for authorization, but i'm an absolute beginner in this topic and in general not really experienced in Java. The API of this library provided me the methods md5, md5hex.
If i'm not mistaken the result of these just differs in the output as a hexString (i'm not even sure whats this means) and regular bytes.
String b1 = DigestUtils.md5hex("Some String");
String b2 = DigestUtils.md5hex("Some String");
The result is 83beb8c4fa4596c8f7b565d390f494e2 & 83beb8c4fa4596c8f7b565d390f494e2
But a comparison with == results in false
if (b1 == b2){
System.out.println("Matching")
}
I'm pretty confused and i can't find a source for an introduction around this topic(for java!)
Because == is not how Strings are compared in Java, use .equals
For example...
if (b1.equals(b2)) {...
"==" means to compare with the values.
If you compare two object-type objects(such as String, Date), the compared value is their unique reference address in the jvm. That means you want to know if they are the same object
If you compare two primitive types(such as int, float, double...), the compared value is their real values.
So if we want to compare two objects, we usually use equals() function instead of "==", because we just want to know if they they have the same attribute values.
Further more, If you define you own class, you should override the equals() function to compare objects of the class.

Check if string array index is equal to string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So I'm trying to check a list of account names to see if the username entered by the operator is in the database or not. At the moment I have:
for(int i = 0; i < rowCount; i ++){
System.out.println("Stored in array:" + accounts[i+1]);
System.out.println("name entered:" + LoginPage.usrname);
if(accounts[i+1] == LoginPage.usrname){
System.out.println("match");
}else{
System.out.println("no match");
}
}
I tried messing around with things like indexOf string and can't get anything to work. I'm sure there's a simple solution, just having trouble finding one. I don't understand why I can't compare a String array index to a String variable, seems like ti should be cake.
This is what you're looking for:
if(acounts[i+1].equals(LoginPage.usrname))
Using the == operator on Strings in Java doesn't do what you think it does. It doesn't compare the contents of the Strings, but rather their addresses in memory. The equals method compares the contents of the Strings.
As a note that may help you remember, this isn't anything particularly special about Strings. Strings are objects, and in Java, using == to compare objects of ANY type will present the same problem. If you want to compare the contents of two objects of a custom class you create, you'll have to write an equals method for that class. Strings work exactly the same.
String are unique reference type that behave like value type.
At Java when trying to compare String's using == operator, Java will try to check if both of the reference are equals, Not the strings.
In order to achieve a value type comparison you will be to use one of the following:
Method 1: str1.equals(str)
Method 2: str1.compareTo(str) == 0

Comparing two strings in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!

Categories