0

How to Convert an Object(not String),like TreeNode.item, into primitive like int.

alan
  • 49
  • 1
  • 2
  • 7
  • 1
    Well what does the Object reference point to? What sort of conversion do you want? – Jon Skeet Apr 02 '10 at 06:54
  • The String to primitive exists because it's quite easy to guess how a string can contain an int, or a double. But how do you transform (what is the algorithm) your TreeNode into an int ? The only way i can envision that is to get the label, then do a string to int conversion. – Riduidel Apr 02 '10 at 06:58
  • 1
    If you want a meaningful conversion, you need to tell us what the `Object` means. – polygenelubricants Apr 02 '10 at 08:22

2 Answers2

6

In response to your last comment: just double-check, that the object is really of type Integer, then use auto-boxing (I assume that your compiler level is 1.5+):

Object o = getTheValue();
int result = 0; // we have to initialize it here!
if (o instanceof Integer) {
  result = (Integer) o;
} else {
  throw new WTFThisShouldHaveBeenIntegerException();
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

hashCode() might be what you want. Then again, it might not.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • 2
    Isn't the same feature also covered by Random.nextInt() ? ;-) – Riduidel Apr 02 '10 at 07:21
  • @Riduidel - no. `hashCode` returns the same value when called again for the same object (unless you change its visible properties). But neither is it unique necessarily between objects (if they have identical visible properties then it is likely to be the same). – Daniel Earwicker Apr 02 '10 at 07:27
  • `hashCode()`'s implementation detail can be changed, better not rely on that – nimcap Apr 02 '10 at 07:39
  • @nimcap - do you mean that it should never be used? Surely you appreciate that it has a purpose? – Daniel Earwicker Apr 02 '10 at 07:40
  • @Daniel - I guess what user307496 is trying to achieve is that there is a string, value etc. contained in a `TreeNode` and he wants to convert that to a int. For that purpose `hashCode()` should not be used. But I see your point, he did not mention what he is trying to do, so as you said` hashCode()` might be what he wants :) – nimcap Apr 02 '10 at 08:23
  • I don't explain clearly just now. My class TreeeNode, has varible T item, and I have a driver class setItem(0), so my case is that the object items are all int, but in my driver class, when I use getItem(), it return Object item, how to convert the item into int type though object item has integer value. – alan Apr 02 '10 at 08:24
  • 1
    @user307496 - it's a boxed integer, so you need Andreas_D's answer. – Daniel Earwicker Apr 02 '10 at 08:52
  • Don't you use generics (`T item`)? If so, you can write it such that you get a boxed `int` back when you use `T getItem()`, then just auto-unbox to get the primitive. – polygenelubricants Apr 02 '10 at 09:16