This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I'm trying to write a method in az DBOpenHelper extends SQLOpenHelper class.
It supposed to evaluate if there's an entry in the DB with the same name.
public boolean existsContact(Contact contact) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(1);
String cname = contact.getName();
if (name == cname) {
cursor.close();
db.close();
return true;
}
} while (cursor.moveToNext());
}
db.close();
return false;
}
Here's the relevant part of Contact class:
public class Contact {
String _name;
public String getName(){
return this._name;
}
}
Now here's the strange thing:
Scenario A : if (name == cname) where name = "foo" and cname = "foo" equals false.
Eclipse debugger show name's foo and cname's foo have different id's.
both variables filled as seen before in code.
Scenario B: if(name == cname) where variabales are loaded like this:
String name = "foo";
String cname = "foo";
statement equals true as it's supposed to.
Scenario C: if("foo" == "foo") equals true...BUT...debugger goes out the window. LogCat show debugger connected, but there's no activity in eclipse's Debug perspective. Breakpoints have no effect. No Threads shown.
In java, when using == on two objects, you're not actually comparing the strings themselves. You'll need to use .equals(String).
== actually compares the two object's references, not their values.
string1.equals(String target) compares the two strings based off of the actual characters in the strings.
See: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html
== operator check object reference are equal or not but equals() method check values are same or not
if (name == cname)
{
cursor.close();
db.close();
return true;
}
change with it
if (name.equals(cname)){
cursor.close();
db.close();
return true;
}
When comparing objects in java that are not primitive data types (int, char, boolean, etc...), you have to use the method Object#equals(Object), which returns a boolean.
So, when you are comparing two Strings, you are actually checking if the two Objects are the same instance, instead of the actual value.
All you have to do is just change name == cname to name.equals(cname).
Related
I have two arrayLists<myObject>, where myObject is an object of a custom class I've created. I want to be able to compare those arrayLists using the equals() method.
After reading and looking for answers, I've read that certain objects like int[] are only considered equal by the equals() method when they are referencing the same thing.
To fix that, I tried to override the equals method in my custom object. My objects have 3 atributes (all basic types), so my equals method now returns true if all the 3 atributes are equal to those of the object compared, and false otherwise. However, comparing the arraylists still doesn't work. What am I doing wrong?
Excuse me for explaining the code instead of posting it, I do it because the variables and names aren't in English.
EDIT: Ok, here's the code. Compra is my custom class; cantidad,concepto and id are its atributes.
#Override
public boolean equals(Object obj) {
boolean result = true;
if (obj == null) {
result = false;
}else{
Compra comprobada = (Compra) obj;
if(!(this.id == comprobada.getId())){
result = false;
}
if(!(this.cantidad == comprobada.getCantidad())){
result = false;
} if(!this.concepto.equals(comprobada.getConcepto())){
result = false;
}
}
return result;
}
Based on this one :
How can I check if two ArrayList differ, I don't care what's changed
If you have implemented your custom object equals correct (you actually override it and have your one) and the size of the arrayList is the same and each of the pair of the objects is equal then it will return equal. In other words what you are trying to do is totally correct but your arrayLists are not actually having exactly the equal objects in exact order.
Make sure that your equal is called when you check for collection equality by doing a System.out.println() to investigate what is going on.
If you don't mind please send the equals of your object.
I run your code in an isolated example and works fine (outtputs true) - I improved the equals method so it doesn't do so many if checks as if only one of them is not equal it should return false.
class stackoverflow {
public static void main(String args[]){
ArrayList<Compra> array1 = new ArrayList<>();
ArrayList<Compra> array2 = new ArrayList<>();
array1.add(new Compra(1,2,"test"));
array2.add(new Compra(1,2,"test"));
System.out.println(array1.equals(array2));
}
}
class Compra {
int id;
int cantidad;
String concepto;
public Compra(int id, int cantidad, String concepto){
this.id = id;
this.cantidad = cantidad;
this.concepto = concepto;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}else{
Compra comprobada = (Compra) obj;
if(!(this.id == comprobada.getId())){
return false;
}
if(!(this.cantidad == comprobada.getCantidad())){
return false;
}
if(!this.concepto.equals(comprobada.getConcepto())){
return false;
}
}
return true;
}
public int getId() {
return id;
}
public int getCantidad() {
return cantidad;
}
public String getConcepto() {
return concepto;
}
}
Some things to check:
Are you sure you don't change the order of the things in ArrayList??:
Do you print to make sure that these equals checks happen and return true or false as expected?
Are you sure that concepto Strings are exactly the same, with the same case and don't contain extra spaces etc?
As you haven't posted code i suggest you to check into Comparable class and method compareTo and how to use it for custom classes.
I am trying to run a getBook() method in a Bookstore program which can allow me to find a book stored in the AL books not only if title and author are correct but also if one of them is null.
So, I wrote this code:
public Book getBook(String author, String title){
boolean condOk = false;
Book book = null;
if(books!=null){
for(int i=0; i<books.size(); i++){
if((author==null && title.equals(books.get(i).getTitle())) ||
(author.equals(books.get(i).getAuthor()) && title==null)){
condOk = true;
book = books.get(i);
break;
} else if(title.equals(books.get(i).getTitle()) &&
author.equals(books.get(i).getAuthor())){
condOk = true;
book = books.get(i);
break;
}
}
}
if(condOk==false) return null;
else return book;
}
The J-Unit test (not created by me) of this part, puts in books 4 objects (with constructor: String title, String author, ...) and then it tests the method getBook() three times: with author and title, with title expressed and author null, and a last time with the opposite situation.
I have already tried something and I noticed that if I substitute all the equals() calls with the logical op == everything works fine.
In the Book class everything is correct, all the getters and setters are in the right place.
So, why do I get such a behavior, when several times I read that comparing Strings with equals() is better than doing it with ==?
You run into a NullPointerException, for example if title is null and author is not equal to a book in the list. The condition of the first if is false, so you enter the else part and the condition of the second if cannot be evaluated because in title.equals(books.get(i).getTitle()) the title is null.
This does not happen if you use ==, it is allowed to compare null values with ==.
I get a string form a list and try to compare it with some strings in the values and then do some stuff
for(int i=0; i<sizeOfList; i++){
String LIST_TITLE;
LIST_TITLE = list_title.get(i); //the List list_title includes some strings
if(LIST_TITLE.equals(R.string.percentbattery)) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.eightsms) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else {
// do stuff
Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
}
}
If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement.
Is there another way to compare these strings? the "==" method also don't work.
R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string.
what u want is:
LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))
LIST_TITLE.equals(R.string.percentbattery)
This is incorrect, because you're trying to compare string with resource ID
You should get the string from resource first:
LIST_TITLE.equals(getResources().getString(R.string.percentbattery))
R.string.xxx is an int. You need to get the String from that res
Something like
if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))
This is assuming you have Activity Context available. Otherwise, you would need to add a Context variable in front of getResources()
R.string.some_id is just an integer by which you can get the String from the resources.
So in order to compare Strings correctly in you case you have to do:
String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...
I have a following problem - if else statements do not work in JSP, and to be honest I have no idea why. Basically I try to change the placeName depending on what number is stored in a string called place. After printing the values in the browser I can see the value is not changed. I am sure it is something simple but... Maybe some one had similar problem before?
<%
//requests the strings sent by previous page
String year = request.getParameter("year");
String place = request.getParameter("place");
out.print(year);
out.print(place);
String year2 = request.getParameter("year2");
String place2 = request.getParameter("place2");
//out.print(year2);
//out.print(place2);
if (place == "1")
{
placeName = "Belmullet";
}
else if (place == "2")
{
placeName = "Birr";
}
...more statements here...
else if (place == "15")
{
placeName = "Shannon airport";
};
%>
change the if condition:
if (place == "1") {
}
by
if ("1".equals(place)) {
}
and the same way for the other if conditions.
This SO question may helps you to learn the difference between == and equals().
It's because you're comparing Strings using ==. Instead, use the .equals() method.
The == operator tests to see if two object references refer to the exact same instance of an object.
The .equals() tests to see if the two objects being compared to each other are equivalent.
I´ve got this method:
public User findById(String name)
{
for (User u : list)
{
if (u.getFirstName() == name)
{
return u;
}
}
return null; // or empty User
}
How can i program a method in my window class so that i can print out the user i´ve found?
This is what i got. (think im way off)
public void findCustomer()
{
String firstname = findCustomerField.getText();
if(!firstname.equals(""))
{
String result = list.findById(firstname);
outputText.setText(result);
}
}
Don't use == in your comparison
if (u.getFirstName() == name)
but equal
if (u.getFirstName().equal(name))
The operator == tests to see if two object reference variables refer to the exact same instance of an object.
The method .equals() tests to see if the two objects being compared to each other are equivalent
You need to change also your findCustomer method like this
public void findCustomer()
{
String firstname = findCustomerField.getText();
if(!"".equal(firstname))
{
User user = list.findById(firstname);
if(user != null)
{
outputText.setText(user.getFirstName());
}
}
}
Use String.equals() for value equality check.
Change this to:
if (u.getFirstName().equals(name)) {
The == basically does object reference equality check.
String result = list.findById(firstname);
Your findById returns a User so change it to:
User result = list.findById(firstname);
Consequently change your next line to:
outputText.setText(result.getFirstName());