I have a simple if statement that doesn't seem to work. I'm out of ideas. I don't understand why my logic is wrong.
String a = "bf";
if (a.compareTo("bf"))
{
// do this
}
I'm getting a redline under the compareTo statement.
Type mismatch: cannot convert from int to boolean
compareTo method returns int value. so do as
if (a.compareTo("bf") == 0)
{
//
}
(or)
use .equals method
if (a.equals("bf"))
{
// do this
}
compareTo returns an int, not a boolean.
http://developer.android.com/reference/java/lang/Comparable.html
It a negative integer if this instance is less than another; a positive integer if this instance is greater than another; 0 if this instance has the same order as another.
So you should check for == 0
By the way, it works for things that can be ordered only. If you just want to check for equality, use .equals
change it to this
String a = "bf";
if (a.compareTo("bf") == 0)
{
// do this
}
The compareTo method returns an int value, not a boolean.
You must change it to
if (a.compareTo("bf") == 0)
or use
if (a.equals("bf"))
When comparing for equality you should use equals(), because it
expresses your intent in a clear way.
compareTo() has the additional drawback that it only works on objects
that implement the Comparable interface.
This applies in general, not only for strings.
Use equals() method of Object class to compare two String objects here.
String a = "bf";
if (a.equals("bf"))
{
// do this
}
Moreover compareTo() is the method of java.lang.Comparable Interface.
compareto returns an integer. An if statement wants a boolean to check so change you code to:
String a = "bf";
if (a.compareTo("bf")==0)
{
// do this
}
Related
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 ==.
I have a custom equals to check the equality of my object called Pair.
class Pair implements Comparable <Parr> {
double coef;
int power;
Pair(double a, int b) {
coef = a;
power = b;
}
My custom equals method is (located in class pair):
#Override
public boolean equals(Object o) {
if (!(o instanceof Pair))
return false;
Pair that = (Pair) o;
return that.coef == this.coef && that.power == this.power;
}
I've checked with print my object if the objects are the same, and they are indeed the same.
1.0 1 2.0 0
1.0 1 2.0 0
I call my custom equals from a different file, called Test.
class Test {
public static void main(String[] args) {
orig = pol1.differentiate().integrate();
System.out.print(orig);
if (orig.equals(pol1))
System.out.println(" (is equal.)");
else
System.out.println(" (is not equal.)");
And my class Polynomial, which is an arraylist with objects of Pair inside.
class Polynominal implements PolynominalInterface {
ArrayList<Pair> terms = new ArrayList<Pair>();
I looked on the internet, and I found that I cannot use == in my Equals method, but I'm using Intergers and Doubles, so equals() would not work.
Can anyone point me in the right direction?
If orig and pol1 are instances of Polynomial then this
if (orig.equals(pol1))
would only work if you implement Polynomial#equals() as well; which would iterate the two ArrayLists and make sure individual Pairs are equal (using Pair#equals() of course).
Ok, thanks to Ravi Thapliyal I found the solution.
After adding an custom equals method in my Polynominal class, the problem was fixed.
#Override
public boolean equals(Object o) {
if (!(o instanceof Polynomial))
return false;
Polynomial that = (Polynomial) o;
return that.terms.equals(terms);
}
Use the Double.compare(double, double) method instead of ==.
Floating point comparison is "fuzzy" in Java.
You would need to implement a Polynomail.equals() method something like the following:
public boolean equals(Object o) {
if (!(o instanceof Polynomial)) return false;
Polynomial other = (Polynomial) o;
if (this.terms==null && other.terms==null) return true;
// A suitable equals() method already exists for ArrayList, so we can use that
// this will in turn use Pair.equals() which looks OK to me
if (this.terms!=null && other.terms!=null) return this.terms.equals(other.terms);
return false;
}
Two issues come to mind: the first is that the default hashCode() method will seldom return the same value for any two distinct object instances, regardless of their contents. This is a good thing if the equals() method will never report two distinct object instances as equal, but is a bad thing if it will. Every object which overrides Object.equals() should also override Object.hashCode() so that if x.equals(y), then x.hashCode()==y.hashCode(); this is important because even non-hashed generic collections may use objects' hash codes to expedite comparisons. If you don't want to write a "real" hash function, simply pick some arbitrary integer and have your type's hashCode() method always return that. Any hashed collection into which your type is stored will perform slowly, but all collections into which it is stored should behave correctly.
The second issue you may be seeing is that floating-point comparisons are sometimes dodgy. Two numbers may be essentially equal but compare unequal. Worse, the IEEE decided for whatever reason that floating-point "not-a-number" values should compare unequal to everything--even themselves.
Factoring both of these issues together, I would suggest that you might want to rewrite your equals method to chain to the equals method of double. Further, if neither field of your object will be modified while it's stored in a collection, have your hashCode() method compute the hashCode of the int, multiply it by some large odd number, and then add or xor that with the hashCode of the double. If your object might be modified while stored in a collection, have hashCode() return a constant. If you don't override hashCode() you cannot expect the equals methods of any objects which contain yours to work correctly.
Normally when you have an object an objects Equals methods is equal to another object of same type if the two hashcodes are alike.
Does Integer work the same way by comparing hashcodes or does it work in a different way?
Two objects that have the same hashcode need not be equals().
Two objects that are equals() must have the same hashcode.
This basically means you may have (occasional) hashcode collisions.
The Integer equals() method simply compares the int value it wraps with the other Integer's int value. Hashcodes don't come into it.
Note that the equals() and hashcode aggrement is not strictly required, but it is relied upon by the numerous JDK classes that use an internal Hashtable, eg the various java.util.Hashxxx classes.
If you check the source of the Integer.java wrapper class, you can find that the equals method has been overridden to check that both the Integer objects have same int value.
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
So you can say JDK compares the integer values inside the object.
Integer equals() method compares int values as == operator does, See below code of Integer.equals() method.
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
Why is it important to you?
Integer#equals checks if two int values are equal, and not just references. So the actual Integer objects might be different (different references), however be equivalent.
I have
String x = g.substring(0, 1);
if (x == "S") {
stuff
}
I have a string, "Safety", but "stuff" doesn't run and my watch say x value = S and x=="S" = false.
== is used for identity comparison, and it checks whether the two reference points to the same object (in your case the object is String).
You should use the equals method to compare the contents of your string:
if (x.equals("S"))
This compares references not string equality x=="S" you should use "S".equals(x).
Use equals() method of String class instead, not ==.
if(x.equals("S"))
== checks the reference and not the value.
You should use the .equals method to compare Strings (and any non-primitives in general).
if (x.equals("S")) {
//stuff
}
Many problems...
Your variable x is a String! You shouldn't use == operator with that, use .equals() instead
Also, while you're at it, you should use .equalsIgnoreCase() to ignore case.
By the way, I should note that there is the String.charAt(int) function too, which returns the character at the specified place...
But if you would like to select all Strings (your question didn't reveal your original intentions why and what you are trying to achieve), but I'd look into regular expressions, and using String.matches()
You need to use String.equals for comparing string content. The == operator is used for comparing object references.
Switching the positions of the arguments will avoid a NullPointerException:
if ("S".equals(x))
In Java equals() checks equality and == checks identity.
Why don't you use the charAt function and do it like this:
char x = g.charAt(0);
if (x == 'S') {
// Stuff
}
If you don't want to use char, use the equals method in the if block comparison as:
String x = g.substring(0, 1);
if (x.equals("S")) {
// stuff
}
I am learning about arrays, and basically I have an array that collects a last name, first name, and score.
I need to write a compareTo method that will compare the last name and then the first name so the list could be sorted alphabetically starting with the last names, and then if two people have the same last name then it will sort the first name.
I'm confused, because all of the information in my book is comparing numbers, not objects and Strings.
Here is what I have coded so far. I know it's wrong but it at least explains what I think I'm doing:
public int compare(Object obj) // creating a method to compare
{
Student s = (Student) obj; // creating a student object
// I guess here I'm telling it to compare the last names?
int studentCompare = this.lastName.compareTo(s.getLastName());
if (studentCompare != 0)
return studentCompare;
else
{
if (this.getLastName() < s.getLastName())
return - 1;
if (this.getLastName() > s.getLastName())
return 1;
}
return 0;
}
I know the < and > symbols are wrong, but like I said my book only shows you how to use the compareTo.
This is the right way to compare strings:
int studentCompare = this.lastName.compareTo(s.getLastName());
This won't even compile:
if (this.getLastName() < s.getLastName())
Use
if (this.getLastName().compareTo(s.getLastName()) < 0) instead.
So to compare fist/last name order you need:
int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
d = getLastName().compareTo(s.getLastName());
return d;
The compareTo method is described as follows:
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.
Let's say we would like to compare Jedis by their age:
class Jedi implements Comparable<Jedi> {
private final String name;
private final int age;
//...
}
Then if our Jedi is older than the provided one, you must return a positive, if they are the same age, you return 0, and if our Jedi is younger you return a negative.
public int compareTo(Jedi jedi){
return this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}
By implementing the compareTo method (coming from the Comparable interface) your are defining what is called a natural order. All sorting methods in JDK will use this ordering by default.
There are ocassions in which you may want to base your comparision in other objects, and not on a primitive type. For instance, copare Jedis based on their names. In this case, if the objects being compared already implement Comparable then you can do the comparison using its compareTo method.
public int compareTo(Jedi jedi){
return this.name.compareTo(jedi.getName());
}
It would be simpler in this case.
Now, if you inted to use both name and age as the comparison criteria then you have to decide your oder of comparison, what has precedence. For instance, if two Jedis are named the same, then you can use their age to decide which goes first and which goes second.
public int compareTo(Jedi jedi){
int result = this.name.compareTo(jedi.getName());
if(result == 0){
result = this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}
return result;
}
If you had an array of Jedis
Jedi[] jediAcademy = {new Jedi("Obiwan",80), new Jedi("Anakin", 30), ..}
All you have to do is to ask to the class java.util.Arrays to use its sort method.
Arrays.sort(jediAcademy);
This Arrays.sort method will use your compareTo method to sort the objects one by one.
Listen to #milkplusvellocet, I'd recommend you to implement the Comparable interface to your class as well.
Just contributing to the answers of others:
String.compareTo() will tell you how different a string is from another.
e.g. System.out.println( "Test".compareTo("Tesu") ); will print -1
and System.out.println( "Test".compareTo("Tesa") ); will print 19
and nerdy and geeky one-line solution to this task would be:
return this.lastName.equals(s.getLastName()) ? this.lastName.compareTo(s.getLastName()) : this.firstName.compareTo(s.getFirstName());
Explanation:
this.lastName.equals(s.getLastName()) checks whether lastnames are the same or not
this.lastName.compareTo(s.getLastName()) if yes, then returns comparison of last name.
this.firstName.compareTo(s.getFirstName()) if not, returns the comparison of first name.
You're almost all the way there.
Your first few lines, comparing the last name, are right on track. The compareTo() method on string will return a negative number for a string in alphabetical order before, and a positive number for one in alphabetical order after.
Now, you just need to do the same thing for your first name and score.
In other words, if Last Name 1 == Last Name 2, go on a check your first name next. If the first name is the same, check your score next. (Think about nesting your if/then blocks.)
Consider using the Comparator interface described here which uses generics so you can avoid casting Object to Student.
As Eugene Retunsky said, your first part is the correct way to compare Strings. Also if the lastNames are equal I think you meant to compare firstNames, in which case just use compareTo in the same way.
if (s.compareTo(t) > 0) will compare string s to string t and return the int value you want.
public int Compare(Object obj) // creating a method to compare {
Student s = (Student) obj; //creating a student object
// compare last names
return this.lastName.compareTo(s.getLastName());
}
Now just test for a positive negative return from the method as you would have normally.
Cheers
A String is an object in Java.
you could compare like so,
if(this.lastName.compareTo(s.getLastName() == 0)//last names are the same
I wouldn't have an Object type parameter, no point in casting it to Student if we know it will always be type Student.
As for an explanation, "result == 0" will only occur when the last names are identical, at which point we compare the first names and return that value instead.
public int Compare(Object obj)
{
Student student = (Student) obj;
int result = this.getLastName().compareTo( student.getLastName() );
if ( result == 0 )
{
result = this.getFirstName().compareTo( student.getFirstName() );
}
return result;
}
If you using compare To method of the Comparable interface in any class.
This can be used to arrange the string in Lexicographically.
public class Student() implements Comparable<Student>{
public int compareTo(Object obj){
if(this==obj){
return 0;
}
if(obj!=null){
String objName = ((Student)obj).getName();
return this.name.comapreTo.(objName);
}
}