Skip to main content
gamedev.net
🔒 Locked

[java] comparing variables of object class in java

Started by ProperFuked 5 replies 700+ views
Original Post
ProperFuked
ProperFuked
Hi, i need some help: in my program i have a class Object variable, which stores some input (could be int, or string or whatever). However - if the input is an integer, i have to be able to compare it to another variable, also of type object (which stores some other int value). I'm trying to find information on casting from object into int, however i'm not having much luck. so i guess what i need is a simple method or procedure, which could cast an Obj variable into an int, so that i can compare them. Oh another thing, i have to be able to compare to see if one is less than or greater than, not just to see if they are equal (that would be easy, i know). Thank you ahead of time for any help.
"Oh, Brother", said Pooh as he was frozen in carbonite.
Lucidquiet
Lucidquiet
Is this homework?

Objects are not primitives, and in java there is no "casting" from an Object to a primitive be it 'int' or 'boolean' or 'char'. What you might need to do however is cast it to some class that has a proper 'get' integer method so that you can compare that integer to some other integer. This in effect allows you to use the methods found in the Class to which you are casting said Object.

If you are trying to compare Object to Object's take a look at the 'Comparator' interface in the API since that will also let you define some behavior for less than, etc. You can also override the method equals(Object o) found in the Object class, in which cas you will have to cast to some appropriate class in order to do the comparison between 'this' class and the one represented as 'o'.

L-

"Education is when you read the fine print; experience is what you get when you don't." -Pete Seegerwww.lucid-edge.net
ProperFuked
ProperFuked
Yes it is and thank you for your help.
"Oh, Brother", said Pooh as he was frozen in carbonite.
pinacolada
pinacolada
You should also check out the Integer class, it's the standard way of passing ints as objects.
H_o_p_s
H_o_p_s
I think you could also do something like this:
if(getSomeRandomObject().getClass().getName().equals("Whatever name your looking for"))
//do what ever

I think… I'm not sure…
BRING BACK THE BLACK (or at least something darker)
Whackjack
Whackjack
Quote:
Original post by H_o_p_s
I think you could also do something like this:
if(getSomeRandomObject().getClass().getName().equals("Whatever name your looking for"))
//do what ever

I think… I'm not sure…


If you're gonna do that, you might as well do

if(object instanceof Foo)
// do whatever

Much faster than trying to do a String comparison (and simpler).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.