This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I do have a simple Object which can be identified by a String. These identifiers are unique.
public class SomeObject
{
private String identifier;
public String getIdentifier() {
return this.identifier;
}
}
I now have another class which holds a List of these simple Objects and has a method to return the object that matches the identifier provided if it exists in the list.
public class SomeBiggerClass
{
LinkedList<SomeObject> allObjects;
public SomeObject getObject(String identifier)
{
if (this.allObjects.stream().anyMatch(object -> object.getIdentifier() == identifier)) {
return this.allObjects.stream().filter(object -> object.getIdentifier() == identifier).findAny().get();
}
else {
return null;
}
}
}
However even if the Strings exactly match it will return false for the anyMatch() part and will throw an exception for the second lambda. I would be alble to do this in c# and linq, however I'm kinda lost with these java lambdas. Any ideas on how to do this would be apreciated.
You need to use .equals(...) instead of == in order to compare strings.
Related
This question already has answers here:
Why Java does not allow overriding equals(Object) in an Enum?
(6 answers)
Closed 6 years ago.
I want to compare Enum's value as in example.
public enum En{
Vanila("Good"),
Marlena("Luck"),
Garnela("Good");
private String value;
private En(String s){
this.value = s;
}
}
AS Vanila and Garnela have the same value comparing them should return true. There are two ways one is == operator and second is equals() method. I tried my own logic and add this method to enum.
public boolean compareValue(En e){
return (this.value).equals(e.value);
}
and Now it's working fine.
En a = En.Vanila;
En b = En.Garnela;
En c = En.Marlena;
if(a.compareValue(b)){
System.out.println("a == b");
}
if(a.compareValue(c)){
System.out.println("a == c");
}
if(b.compareValue(c)){
System.out.println("b == c");
}
I know we can't override equals methods in enum ( Don't know why, I know that is final but not a logically reason. Can you also explain, why we can't override equals() in enum?).
Any how is there any other way to do this effectively or is it fine?
In enum each instance is meant to represent a distinguished thing. The enum value is used to describe that thing, make it human readable, etc.
Therefore there's no reason for your code to consider that Vanilla could be equal to Marlena. And it makes no sense to set the same string values for both of them.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
why the result is false?
could someone please explain?
public class StringTest1 {
public static void main(String[] args) {
String a="a";
String b=a+"b";
String c="ab";
System.out.println(b==c);
}
}
Because they don't point to the same object in the memory.
== is used for comparison of either primitive types, or object references.
What you want to do, is to compare their values, for which you 'll need to use the equals(Object o) or equalsIgnoreCase(Object o) method(s)
Output of this comparison is FALSE because you have created two
objects which have different location in heap so == compare their
reference or address location and return false.
Read more: http://java67.blogspot.com/2012/11/difference-between-operator-and-equals-method-in.html#ixzz3xmRzfSkP
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public static void main(String[] args) {
Integer i = new Integer(4);
System.out.println(i.toString());
if (i.toString() == i.toString()) {
System.out.println("true how");
} else {
System.out.println("false how");
}
}
While executing above code, I am getting output as "false how".
Can you explain how Jvm treats this object?
toString() creates a new string object every time and your code is actually checking if both references are the same, which is never the case so it runs the else case. If you try
i.toString().equals(i.toString())
you'll get the desired output.
You must compare objects with equals() method.
i.toString().equals(i.toString())
This question already has answers here:
ArrayList contains case sensitivity
(20 answers)
Closed 9 years ago.
I have an ArrayList();
List<String> list = new ArrayList<>();
list.add("aaa");
list.add("BBB");
list.add("cCc");
System.out.println(list.contains("aAa"));
Here i want to check contains() method with equalsIgnoreCase method in same line.
How can i do it?
boolean containsEqualsIgnoreCase(Collection<String> c, String s) {
for (String str : c) {
if (s.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
You can't. The contract of contains is that it defers to equals. That's a fundamental part of the Collection interface. You have to write a custom method that iterates through the list and checks each value.
This is an interesting question from an OO perspective.
One possibility is to transfer the responsibility of the contract you want to enforce (equality without case) to the collected elements themselves, not to the list, with respect to a proper separation of concern.
You would then add a new class for your String objects (without inheritance, String class is final) where you would implement your own hashCode/equals contract.
// Strictly speaking, this is not a String without case, since only
// hashCode/equals methods discard it. For instance, we would have
// a toString() method which returns the underlying String with the
// proper case.
public final class StringWithoutCase {
private final String underlying;
public StringWithoutCase(String underlying) {
if (null == underlying)
throw new IllegalArgumentException("Must provide a non null String");
this.underlying = underlying;
}
// implement here either delegation of responsibility from StringWithoutCase
// to String, or something like "getString()" otherwise.
public int hashCode() {
return underlying.toLowerCase().hashCode();
}
public boolean equals(Object other) {
if (! (other instanceof StringWithoutCase))
return false;
return underlying.equalsIgnoreCase(other.underlying);
}
}
The objects populating the collection would be instances of StringWithoutCase :
Collection<StringWithoutCase> someCollection = ...
someCollection.add(new StringWithoutCase("aaa"));
someCollection.add(new StringWithoutCase("BBB"));
someCollection.add(new StringWithoutCase("cCc"));
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Java String.equals versus ==
whats the difference between ".equals and =="
public String getName() {
return new String("foobar");
}
if(getName() != "foobar2") {
//Never gets executed, it should, wtf!.
}
if(!getName().equals("foobar2")) {
//This works how it should.
}
So yeah my question is simple.. why doesn't != behave the same as !equals() aka (not Equals).
I don't see any logicial reason why one should fail, both are the same exact code in my mind, WTH.
Looking at java operators
http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
You can clearly see
equality == !=
are the equality operators, sure I usually use != only on numbers.. but my mind started wandering and why doesn't it work for String?
EDIT:
Here's something that looks more like the actual issue..
for (ClassGen cg : client.getClasses().values()) {
final ConstantPoolGen cp = cg.getConstantPool();
if(cp.lookupInteger(0x11223344) != -1) {
for (Method m : cg.getMethods()) {
System.out.println("lots of class spam");
if(m.getName() != "<init>") continue;
System.out.println("NEVER GETS HERE, 100% SURE IT HAS CONSTRUCTOR LOL");
}
}
}
Using != means that you check for the instance reference in the memory, and the same instance will give you true on that comparison.
When you do a new String("foobar"), a new "foobar" is created in the memory, and the comparison using == returns false.
Calling a intern() on that new string may change this behavior, since the String will now be grabbed or added to the String pool.
In any case, it's safer to use the 'equals()'.
public static void main(String[] args) throws Exception {
if (getName() != "foobar2") {
System.out.println("1");
}
if (!getName().equals("foobar2")) {
System.out.println("2");
}
}
public static String getName() {
return new String("foobar");
}
For me this outputs:
1
2
But those two checks are not equivalent. The first check is checking whether the object returned by getName() is the same object that was created for the string literal "foobar2", which it's not. The second check is probably the one you want, and it checks that the VALUE of the String object returned by the getName() method is equal to the VALUE of the String object created for your "foobar2" string literal.
So both checks will return true, the first one because they aren't the same object and the second one because the values aren't the same.
A string is an Object, not a primitive.
== and != compare two primitives to each other.
To compare strings you need to loop trough each character and compare them in order which is what .equals() does.
If you do any OOP in Java you need to override equals when you want to do equality checks on the Objects, and implement Comparable and .compare() if you want to be able to do things like sort them.
Here is a quick example of equals:
public class Person {
public name;
public Person(String name) {
this.name = name;
}
public boolean equals(Object o){
if(o instanceof Person)
if(this.name.equals(o.name))
return true;
return false;
}
}
Now a Person can be compared to another Person like:
person1.equals(person2)
Which will only return true if both people have the same name. You can define what makes two objects equal however you want, but objects are only == if they are really just two pointers to the same object in memory.
Operators only apply to primitives, not Objects, so a String comparison must be done equals, as that operates at the Object level.
--EDIT--
My comment was meant more along the lines of "the value of an Object cannot be compared in the expected way as in other languages". Of course you can use == signs, but not for a textual comparison. This is the classic question that is asked every time someone migrates to Java from a scripting language, or another language that does support operators for text comparison on Strings.