wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes int---->integer array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "int---->integer array" Watch "int---->integer array" New topic
Author

int---->integer array

Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
Is there any way to convert a given integer to an integer array.

eg int=1234 ----> int[] ={1,2,3,4}


SCJP 6.0 96%

(Connecting the Dots ....)
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1660
    
  11

Maybe change it to a string, then a character array, then to an Integer array?

There must be a better way....


When you do things right, people won't be sure you've done anything at all.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Divide and conquer.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19674
    
  18

The problem with dividing is that you have to loop twice; once to get to know the array size, then another to fill it. Even if you use a List you still need to loop twice; the second loop to convert a List<Integer> to an int[].
Then again, converting to String and then converting each separate character to a digit (using Character.digit) also is two loops; the int to String also has a loop.

I don't think you can get past a double loop. That leaves an option between ease (int -> String, char -> int) and efficiency (dividing). Well, if dividing is more efficient; I'd have to test first.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: int---->integer array