Comparator compare method() int cannot be dereferenced [duplicate] - java

This question already has answers here:
"int cannot be dereferenced" in Java
(8 answers)
Closed last year.
I'm doing some assignment work and I've struck a problem.
I've been given this example code:
public class PersonNameComparator implements Comparator<Person>{
public int compare(Person p1, Person p2) {
int retValue = p1.getName().compareTo(p2.getName());
if (retValue != 0)
return retValue;
else if (p1.getAge() < p2.getAge())
return -1;
else if (p1.getAge() > p2.getAge())
return 1;
else
return 0;
}
}
However, when I try to do this, this happens:
public class DVDComparator implements Comparator <DVD> {
public int compare(DVD d1,DVD d2)
{
int stars1 = d1.getNoOfStars().compareTo(d2.getNoOfStars());
//ERROR - int cannot be dereferenced.
Any ideas?

You get this error message since getNoOfStars() returns a primitive int and there is no method compareTo() defined for primitive types.
If you're using Java SE 7 you can use something like this:
public class DVDComparator implements Comparator <DVD> {
public int compare(DVD d1,DVD d2){
return Integer.compare(d1.getNoOfStars(), d2.getNoOfStars());
}
}

You don't need to call a method to compare primitive ints. In fact, as you've discovered, you can't.
Just use the normal <, >, and == operators to compare ints.
Just make sure to follow the contract of compare -- return an int less than 0, equal to 0, or greater than 0, if d1 is "less than" d2, if d1 is "equal to" d2, or d1 is "greater than" d2, respectively.
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

int being a primitive is not an object and thus does not have any methods. So when you try and call .compareTo on it, you get an error.
To compare ints, you can use the standard comparison operators < > ==, or you could wrap it in an Integer Object and use the compare method as you are doing now. Although the former is favorable.

// If Person.getName() returns a string then you could simply do the following to // implement Comparable:
public class PersonNameComparator implements Comparator<Person>{
public int compare(Person p1, Person p2) {
return p1.getName() - p2.getName(); // It's the ninja way to do it
}
}

You can find the reason for above error through this link.
You can use one of following approaches which are simple to understand. (sorting in ascending order)
if(d1.getNoOfStars() != d2.getNoOfStars())
return d1.d1.getNoOfStars() - d2.getNoOfStars();
or
if(d1.getNoOfStars() != d2.getNoOfStars())
return d1.d1.getNoOfStars() > d2.getNoOfStars() ? 1 : -1;

Related

Using comparable in a method in the main method

I am trying to check the values of a comparable method and assign the 1 and -1 value to true and false. I made a simple if else statement that does just that but I want to make it inside of a method so I can use it multiple times in my main method. When I try to do this I get an error that my compareTo method (in another class) is "undefined for the type Object".
Here is my code for both the compareTo method and my attempt of using this in my test class.
public int compareTo(FPNumber o) {
if ((exp == o.exp) && (fraction - o.fraction < SMALL))
return 1;
else if ((exp == o.exp) || (fraction - o.fraction > SMALL))
return -1;
else
return 0;
}
public String compare(Object FP1, Object FP2) {
if (FP1.compareTo(FP2) == 1)
System.out.println("true");
else if (FP1.compareTo(FP2) == -1)
System.out.println("false");
else
System.out.println("error");
}
Let me start by a simple example using raw values, and then expand it to use objects.
Suppose you have two variables x and y that hold integer values. If I ask you, how do you know if the values for these variables are equal? The question is answered by simple math: if the values of the two variables are equal, the difference between the two must be zero. For example, 5 - 5. In this case, the difference is zero because both variables hold the value of positive 5.
What if they are different? Let x = 5 and y = 13.
x - y = -8 (this means that x < y)
y - x = 8 (same as above)
As you can see, when the values are different, it is not always going to be 1 or -1. This is important when you are comparing more than two values. Let's introduce z = 20. If comparing x to y and x to z and the result was -1 on both comparisons, the implication is that y and z must be equal but they are not.
What about when comparing objects? It is the same principle. Even when an object holds multiple variables, you must decide a hierarchy to determine which variable is more or less important in the comparison. Consider the following example
public class Person implements Comparable<Person> {
private String firstName;
private String lastName;
private int age;
...
public int compareTo(Person other) {...}
}
I can decide that, for my system, when comparing two Person objects, I must check first the last name, then the first name, and lastly the age.
public int compareTo(Person other) {
int i = lastName.compareTo(other.lastName);
if (i != 0) return i;
i = firstName.compareTo(other.firstName);
if (i != 0) return i;
return Integer.compare(age, other.age);
}
Basically, if the last names are the same (i == 0), it will compare the first names. Then if the first names are the same, it will compare the ages. At any point, if the values are different, the difference will be returned. Again, not a 1 or -1. So basically, to convert the results to boolean, the logic is
public boolean compare(Person person, Person other) {
if (person.compareTo(other) == 0) return true;
else return false;
}
By the way, your original code has a compilation error because your compare method should return a String and it returns void. Instead of using System.out.print() inside your method, like you have now, you should print out the output of the method.
public String compare(Object FP1, Object FP2) {
if (FP1.compareTo(FP2) == 1)
return "true";
else if (FP1.compareTo(FP2) == -1)
return "false";
else
return "error";
}
...
System.out.println(compare(FP1, FP2));
UPDATE: I forgot to mention before that, essentially, the compare function I included here is serving basically the same function as the equals() method. Also, because this function is provided by a third party, it is sort of what a Comparator should do. Because of that, it should be done following best practices of what a Comparator should do. For my Person comparator, you may have two Comparators: one that compares age and one that compare names.

CompareTo Method and running time Assistance [duplicate]

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);
}
}

How does compare method work?

The program sorts the array in ascending order but on swapping id and compareid in the return statement the array sorts in descending order but it has no effect on the output of System.out.println(e[1].compareTo(e[0])); it returns 1 in both cases. Why is it so?
package example;
import java.util.Arrays;
class Example implements Comparable<Example> {
int id;
public int compareTo(Example ob) {
int compareid = ob.id;
return Integer.compare(id, compareid); // problem
}
}
class comparableinterface {
public static void main(String args[]) {
Example e[] = new Example[3];
e[0] = new Example();
e[0].id = 2;
e[1] = new Example();
e[1].id = 3;
e[2] = new Example();
e[2].id = 0;
Arrays.sort(e);
for (Example temp : e) {
System.out.println(temp.id);
}
System.out.println(e[1].compareTo(e[0]));
}
}
Because your comparison is being performed after you have sorted the array, and Arrays.sort(e) changes the contents of the array e.
Move
System.out.println(e[1].compareTo(e[0]));
to before the sort, and it will behave as you expected.
The result of compareTo reflects a certain order between the object and the argument. This will always be +1 between the first and second in a sorted array, sorted according to whatever is expressed by compareTo.
It is not an indication of the numeric relation!
You are using Integer.compare(id,compareid) in your overrided compareTo(Example ob) method, and for your information,
Integer.compare(id,compareid) returns the value 0 if id == compareid; a value less than 0 if id < compareid; and a value greater than 0 if id > compareid.
And you are calling compareTo(Example ob) after sorting the array, this is why the method always returning 1.
Try calling compareTo(Example ob) before sorting the array.
compareTo method is referred to as its natural comparison method.
The natural ordering for a class C is said to be consistent with
equals if and only if e1.compareTo(e2) == 0 has the same boolean value
as e1.equals(e2) for every e1 and e2 of class C.
Ref
See also the java.utils.Arrays.mergeSort() source code to see how compareTo is used to sort an array:
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
Because in order to sort your array ascending/descending you also change your compareTo method in example to compare for < respectively > (i.e. you swap the logic in the compareTo method). That's why it gives you the same result from System.out.println(e[1].compareTo(e[0]));. Basically after the change, your compareTo does not check for "is smaller" any more but checks for "is bigger". So even though System.out.println(e[1].compareTo(e[0])); returns 1 in both cases, in the first case it tells you "e[1] is bigger than e[0]" and in the second case it tells you "e[1] is smaller than e[0]". It's kind of tricky, think about it.
You should call the compareTo() method on an instance of an Integer, not the static compare()
Try this:
int id;
public int compareTo(Example ob) {
Integer compareid = ob.id;
return compareid.compareTo(id);
}

Java CompareTO with double Values

I need to be able to rearrange a group of people from their overall fitness score. I am able to do a compareTO method with ints but as soon as its with doubles I get errors flying up everywhere.
public double compareTo(FitnessScore o){
return (this.overall-o.overall);
}
It needs to be a double because there are scores like:
68.5 68.4 60.1 60.3
So casting them to an int would make it redundant. When I did have it as an int to see if it would work. I tried the following. (subjects being the array that I initialized to hold all the different instances of people)
Arrays.sort(subjects);
I get the following error:
java.lang.NullPointerExceptione
Any suggestions?
Your compareTo must alaways return an int value.
-1 for placing it before in Collection
0 indicates same value already exists in Collection
+1 for placing it afterwards in Collection
If overall is of type Double, use this:
public int compareTo(FitnessScore o){
return this.overall.compareTo(o.overall));
}
If overall is of type double, use this:
public int compareTo(FitnessScore o){
if(this.overall<o.overall)
return -1;
else if(o.overall<this.overall)
return 1;
return 0;
}
And for your NullPointerException, check that your subjects is not null.
You are breaking the signature of compareTo method.
It should look like below,
public int compareTo(FitnessScore o){
return Double.compare(this.overall-o.overall);
}
You need to implement the Comparator interface. Dont worry about your values. Even if the compare method is returning an int. This int is not one of your values.
Also check this out.
Comparator with double type
Your compareTo() method receives a FitnessScore object. However, it does not test for null case.
When o is null, your method will throw a NullPointerException.
You can try this.
Double obj1 = this.overall;
Double obj2 = o.overall;
int retval = obj1.compareTo(obj2);
//then do your normal if else block.
You should implement a Comparator interface:
class OFSComparator implements Comparator<Member> {
public int compare(Member m1, Member m2) {
return (m1.ofs.compareTo(m2.ofs));
}
}
Each Member should have a field for overall fitness score
Double ofs;
And if you later want to sort members based on their overall fitness score, you can use Arrays.sort:
Arrays.sort(members, new OFSComparator());

How does comparator work?

I thought the Collections.binarySearch()would return never return a 0 cause the comparison in the comparator is between two Integer which the == operation would always been false, but the run results let me down... Can someone help me out?
public class ObjectCompare {
static Comparator<Integer> com = new Comparator<Integer>(){
public int compare(Integer i, Integer j) {
return i<j?-1:(i==j?0:1);// i thought i==j would never return true
}
};
public static void main(String[] args){
String[] array = {"0","1","2","3","4","5"};
List<Integer> list = new ArrayList<Integer>();
Integer k = new Integer(1);
Integer l = new Integer(1);
System.out.println(k==l); // this return's false
for(String s : array)
list.add(Integer.valueOf(s));
System.out.println(Collections.binarySearch(list,1,com));// this returns 1
}
}
If I understand well, the question is "why does the binarySearch actually find the item in the list, when my comparator compares instances?" Right?
Well, the answer is as simple as that: because actually it compares two identical instances (references). Integer class maintains a pool of cached instances for values between -128 and 127 (inclusive). This pool of instances is always used when valueOf is called with an argument between these values.
Here you have 2 calls to valueOf(1) (more or less explicit) in your code.
One is here: list.add(Integer.valueOf(s));. For one iteration through the loop, the call is actually list.add(Integer.valueOf("1"); Behind the scenes, valueOf(int) is called.
And the second is here: Arrays.binarySearch(array,1,com). The boxing operation from the literal 1 to the Integer instance is actually performed via an invocation of valueOf(int).
System.out.println(k==l);
This would return false as they are different objects. As known, you need to use equals() method to compare the values of two Integer objects.
return i<j?-1:(i==j?0:1);
This is the return statement of the compare() method. i will not be equal to j unless the same object is present in twice in the list. Note that the compare() method is called by the Collections.sort(list, comparator) method internally. This is not called by the binarySearch() method directly.
System.out.println(Collections.binarySearch(list,1,com));
This returns 1, but the 1 here represents the index at which the search item was found. It would return 3 if your search item was System.out.println(Collections.binarySearch(list,3,com));. The 1 returned by binarySearch() is not from the compare() method. The binary search algorithm will internally call the equals() method to compare the Integer values during the search.
Hence, the i == j clause in the compare() which you thought would never satisfy, has nothing to do with the actual binary search which is performed on the list of Integers.
From the docs of Collections.binarySearch(List, searchItem, comparator):
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator (as by the sort(List, Comparator) method), prior to making this call.
use this
System.out.println(k.equals(l)); // this return's true
instead of
System.out.println(k==l); // this return's false
because == this compare the address of your integer objects not value...
return i<j?-1:((i.equals(j))?0:1);// i thought i==j would return true
instead of
return i<j?-1:((i==j)?0:1);// i thought i==j would never return true
Integer is the boxed variant of int, i.e. a reference type. You need to use the Integer#equals method to test for equality as == will just test if the references are equal:
static Comparator<Integer> com = new Comparator<Integer>(){
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i.equals(j) ? 0 : 1);
}
};
Edit
Now that I think about it, writing a Comparator for Integer is kind of pointless, since Integer already implements Comparable<Integer>.
I've taken the liberty to re-shape the program to focus on the question at hand: the i == j in the compare() method:
import java.util.Arrays;
import java.util.Comparator;
public class StackOverflow {
static Comparator<Integer> com = new Comparator<Integer>(){
#Override
public int compare(Integer i, Integer j) {
int res = 0;
if(i<j){
res = -1;
} else if(i == j ){
res = 0;
} else {
res = 1;
}
return res;
}
};
public static void main(String[] args){
Integer[] array = {0,1,2,3,4,5};
System.out.println(Arrays.binarySearch(array,1,com));
}
}
If you debug/step through the code you do see that when comparing 1 with 1, the code goes into the res = 0. This is likely to be an autoboxing quirck? Maybe as it has to auto-unbox them for i

Categories

Resources