I am to write a method which will implement the compareTo method to compare the objects in my array to decide which is the biggest. Here is my code:
public static Object max(Object[] array) {
for (int i = 0; i < array.length; i++) {
Object lol = (array[0].compareTo(array[i]));
}
return; // what should be returned?
}
Could anyone explain to me how to actually use compareTo, and what it should return?
You are going to need something like this.
Object biggestObject = array[0];
for (Object obj: array){
if (biggestObject.compareTo(obj) == 1){
biggestObject = obj;
}
}
return biggestObject;
If you are using a custom object you are going to need to override the compareTo method so like if the object is a person and we are comparing Pen... feet size, then we would want to set up compareTo to compare feet sizes, returning 1 when the object being compared to is bigger, 0 if its the same, and -1 if its smaller.
#Override
public int compareTo(Object obj){
if (this.feetSize < obj.getFeetSize()){
return 1;
etc, etc....
Related
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.
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);
}
}
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);
}
I have created my own class of which I want to create my TreeSet. My class looks like this :
class mytree implements Comparable
{
int line_no;
line_segment line[];
public int compareTo(Object obj)
{
tree t = (tree)obj;
if(this.line_no == t.line_no)
return 0;
if(this.line[line_no]>t.line[line_no])
return 1;
else
return -1;
}
}
I am defining new objects of the class and then inserting them into the TreeSet.
In cases I am finding out
values like
mytree up = tree.lower(n1);
mytree down = tree.higher(n2);
but if I try to check whether the values of up and down exist in the tree then it sometimes happen that the tree says that the values don't exists in the tree and sometimes it says the values do exist. Though I have handled the case of 0 in compare method what could be the possible error in my creating of the tree.
There are many things wrong in this code. First of all, you're not respecting the Java conventions at all. Second, you're not using generics, as if we were still in 2004, when Java 5 didn't exist yet. Third, your class doesn't represent a tree, so it shouldn't be named mytree. Fourth, your compareTo() method is wrong. It's supposed to be symmetric:
A > B <==> B < A
If A and B's line[line_no] are equal, then if you compare them with A.compareTo(B), the comparison method will return -1. And if you compare them with B.compareTo(A), it will return -1 as well. So you have A < B and B < A at the same time.
if(this.line_no == t.line_no)
return 0;
if(this.line[line_no]>t.line[line_no])
return 1;
You're comparing two different things in these two checks. I'd expect you should be comparing the same thing, e.g.
if(this.line_no == t.line_no)
return 0;
if(this.line_no > t.line_no)
return 1;
or
// also note you probably mean t.line[t.line_no] instead of t.line[line_no]
if(this.line[line_no] == t.line[t.line_no])
return 0;
if(this.line[line_no]>t.line[t.line_no])
return 1;
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