• Advertisement
Sign in to follow this  

[Ask] Java Object Comparison

This topic is 4269 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 :)

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement