[Ask] Java Object Comparison

Started by
4 comments, last by LizardCPP 17 years, 9 months ago
Hi all.. i have something to ask.... How we compare the object data type whether it is greater or lesser..in Java...?? i have trying to use .compareTo() but it still get me an error... thanks before :)
Advertisement
You are going to want to use the equals method. This is build into the Object class so it's valid for all classes but you really want to override it to do anything custom (it compairs memory addresses by default). to do this go something like this:

public class Vector2{    float x,y;    public boolean equals(Object other){        if(!object.instanceOf(Vector2))            return false;        Vector2 vect = (Vector2) other;        if(x=vect.x && y=vect.y)             return true;        return false;    }}


This is just off the top of my head but it should give you the idea
Quote:Original post by Personal_Worker
Hi all..

i have something to ask....

How we compare the object data type whether it is greater or lesser..in Java...??

i have trying to use .compareTo() but it still get me an error...

thanks before :)


compareTo is part of the Comparable interface, which is the standard means of doing what you want. It is designed to work with the Collections API. You can sort lists, arrays, or other Collections according to the implementation of compareTo. But you do need to implement it yourself.

What sort of error are you getting?
Thanks for the answer...i am trying now...thanks...:)
The compiler give this error...

"Cannot resolve symbol method compareTo(java.lang.Object)"
Quote:Original post by Personal_Worker
The compiler give this error...

"Cannot resolve symbol method compareTo(java.lang.Object)"


Thats becasue you have to implement it.


class YourClass implements Comparable
{
// Your methods...



// Implemting Comparable interface

pulic int compareTo(Object other)
{
// Implement this to return 0 if the to objects are equal, -1 if this obejct
// is less than the other obejct, 1 if this obejct is greater than the other
// object
}
}

This topic is closed to new replies.

Advertisement