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;
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 have a class for which equality (as per equals()) must be defined by the object identity, i.e. this == other.
I want to implement Comparable to order such objects (say by some getName() property). To be consistent with equals(), compareTo() must not return 0, even if two objects have the same name.
Is there a way to compare object identities in the sense of compareTo? I could compare System.identityHashCode(o), but that would still return 0 in case of hash collisions.
I think the real answer here is: don't implement Comparable then. Implementing this interface implies that your objects have a natural order. Things that are "equal" should be in the same place when you follow up that thought.
If at all, you should use a custom comparator ... but even that doesn't make much sense. If the thing that defines a < b ... is not allowed to give you a == b (when a and b are "equal" according to your < relation), then the whole approach of comparing is broken for your use case.
In other words: just because you can put code into a class that "somehow" results in what you want ... doesn't make it a good idea to do so.
By definition, by assigning each object a Universally unique identifier (UUID) (or a Globally unique identifier, (GUID)) as it's identity property, the UUID is comparable, and consistent with equals. Java already has a UUID class, and once generated, you can just use the string representation for persistence. The dedicated property will also insure that the identity is stable across versions/threads/machines. You could also just use an incrementing ID if you have a method of insuring everything gets a unique ID, but using a standard UUID implementation will protect you from issues from set merges and parallel systems generating data at the same time.
If you use anything else for the comparable, that means that it is comparable in a way separate from its identity/value. So you will need to define what comparable means for this object, and document that. For example, people are comparable by name, DOB, height, or a combination by order of precedence; most naturally by name as a convention (for easier lookup by humans) which is separate from if two people are the same person. You will also have to accept that compareto and equals are disjoint because they are based on different things.
You could add a second property (say int id or long id) which would be unique for each instance of your class (you can have a static counter variable and use it to initialize the id in your constructor).
Then your compareTo method can first compare the names, and if the names are equal, compare the ids.
Since each instance has a different id, compareTo will never return 0.
While I stick by my original answer that you should use a UUID property for a stable and consistent compare / equality setup, I figured I'd go ahead an answer the question of "how far could you go if you were REALLY paranoid and wanted a guaranteed unique identity for comparable".
Basically, in short if you don't trust UUID uniqueness or identity uniqueness, just use as many UUIDs as it takes to prove god is actively conspiring against you. (Note that while not technically guaranteed not to throw an exception, needing 2 UUID should be overkill in any sane universe.)
import java.time.Instant;
import java.util.ArrayList;
import java.util.UUID;
public class Test implements Comparable<Test>{
private final UUID antiCollisionProp = UUID.randomUUID();
private final ArrayList<UUID> antiuniverseProp = new ArrayList<UUID>();
private UUID getParanoiaLevelId(int i) {
while(antiuniverseProp.size() < i) {
antiuniverseProp.add(UUID.randomUUID());
}
return antiuniverseProp.get(i);
}
#Override
public int compareTo(Test o) {
if(this == o)
return 0;
int temp = System.identityHashCode(this) - System.identityHashCode(o);
if(temp != 0)
return temp;
//If the universe hates you
temp = this.antiCollisionProp.compareTo(o.antiCollisionProp);
if(temp != 0)
return temp;
//If the universe is activly out to get you
temp = System.identityHashCode(this.antiCollisionProp) - System.identityHashCode(o.antiCollisionProp);;
if(temp != 0)
return temp;
for(int i = 0; i < Integer.MAX_VALUE; i++) {
UUID id1 = this.getParanoiaLevelId(i);
UUID id2 = o.getParanoiaLevelId(i);
temp = id1.compareTo(id2);
if(temp != 0)
return temp;
temp = System.identityHashCode(id1) - System.identityHashCode(id2);;
if(temp != 0)
return temp;
}
// If you reach this point, I have no idea what you did to deserve this
throw new IllegalStateException("RAGNAROK HAS COME! THE MIDGARD SERPENT AWAKENS!");
}
}
Assuming that with two objects with same name, if equals() returns false then compareTo() should not return 0. If this is what you want to do then following can help:
Override hashcode() and make sure it doesn't rely solely on name
Implement compareTo() as follows:
public void compareTo(MyObject object) {
this.equals(object) ? this.hashcode() - object.hashcode() : this.getName().compareTo(object.getName());
}
You are having unique objects, but as Eran said you may need an extra counter/rehash code for any collisions.
private static Set<Pair<C, C> collisions = ...;
#Override
public boolean equals(C other) {
return this == other;
}
#Override
public int compareTo(C other) {
...
if (this == other) {
return 0
}
if (super.equals(other)) {
// Some stable order would be fine:
// return either -1 or 1
if (collisions.contains(new Pair(other, this)) {
return 1;
} else if (!collisions.contains(new Pair(this, other)) {
collisions.add(new Par(this, other));
}
return 1;
}
...
}
So go with the answer of Eran or put the requirement as such in question.
One might consider the overhead of non-identical 0 comparisons neglectable.
One might look into ideal hash functions, if at some point of time no longer instances are created. This implies you have a collection of all instances.
There are times (although rare) when it is necessary to implement an identity-based compareTo override. In my case, I was implementing java.util.concurrent.Delayed.
Since the JDK also implements this class, I thought I would share the JDK's solution, which uses an atomically incrementing sequence number. Here is a snippet from ScheduledThreadPoolExecutor (slightly modified for clarity):
/**
* Sequence number to break scheduling ties, and in turn to
* guarantee FIFO order among tied entries.
*/
private static final AtomicLong sequencer = new AtomicLong();
private class ScheduledFutureTask<V>
extends FutureTask<V> implements RunnableScheduledFuture<V> {
/** Sequence number to break ties FIFO */
private final long sequenceNumber = sequencer.getAndIncrement();
}
If the other fields used in compareTo are exhausted, this sequenceNumber value is used to break ties. The range of a 64bit integer (long) is sufficiently large to count on this.
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);
}
Can someone please explain to me what the following code does. I am new to programming. I am having a hard time understanding what is meant by "the current object."
This code is contained within a class that implements the Compareable interface. It has a conscutor that takes an int number and String description. It also has a get method for both number and description.
#Override
public int compareTo (Object o)
{
Item i = (Item) o;
if (this.getNumber () < i.getNumber())
return -1;
if (this.getNumber () > i.getNumber())
return 1;
return 0;
Item i = (Item) o;
This line casts the incoming object o as the Item class, then stores it on i.
if (this.getNumber () < i.getNumber())
This line compares the object you're receiving to the one you're calling the method from, particularly their number fields.
return 0;
This line is only reached if none of the previous conditionals were met. In this case, it returns 0 when this.getNumber() equals i.getNumber().
int x = objectOne.compareTo(objectTwo);
This hypothetical line would assign the corresponding return value to x.
For example, if objectOne.getNumber() is less than objectTwo.getNumber(), x would be assigned a -1 value.
compareTo() returns an int to indicate whether or not the compared value is bigger (1), equal (0) or smaller (-1). What's the problem?