-
Java stacks
I have a stack that I need to add integers to. The problem is that the push method in the Stack class only takes an object variable, not ints or doubles or anything. How can I convery my int into an object to add to the stack?
-
Java has a class called Integer for this.
-
Re: Java stacks
Originally posted by JoeyJoeJo
I have a stack that I need to add integers to. The problem is that the push method in the Stack class only takes an object variable, not ints or doubles or anything. How can I convery my int into an object to add to the stack?
Each of the primitives has a corresponding Object of the same name which you should use.
"You are not beaten until you admit it." --George S. Patton
"Reading and learning, it's what linux users do"
"Double clicking" doesn't work on Linux
G4L | ZSH - The Z Shell
Apple OS X, FreeBSD, and Smoothwall
-
Thanks guys, that did it. Here is what I did so anyone else needing help with this will know. (Most of the program was omitted. These are just the relevent parts)
Code:
private Integer stk;
private int remainder;
stk = new Integer(remainder);
stack.push(stk);
-
I think Java 1.5.0 does automatic "boxing" (i.e. turning an int variable into an Integer object when required) and "unboxing" (the reverse of the above) for you, which means you don't have to think about it in that version. But if you're using something older, then you do have to worry about it.
-
Yeah, the class I'm in uses 1.4.2, or 1.4.something, I don't remember for sure. Is 1.5 out yet? I've heard a lot of talk about it, but I haven't checked to see if it is out.
-
1.5 has been out for a while, and allows the use of templates (similar to c++, though a very different implementation "under the hood"), along with the standard use of Object as a generic.
-
Java offers wrapper classes for every data type (e.g Integer,Double etc)
The catch is that these objects are immutable,that is, you can't modify the value they hold (or scientifically said no modif of their current instance)
However, wrapper classes are the way to go in your case.
_________________________
Registered Linux User #314213
_________________________
Desktop 1 : P4 3.2G HT 2GB TWINX CORSAIR 2X120GB S-ATA NV7800GT- Ubuntu 7.04 - Feisty Fawn
Desktop 2 : P4 2.4G 512MB SDRAM 60GB IntelGMA - Slackware 11 - Fluxbox
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|