| Author |
String.format() - can i pass array ?
|
Mohammed Yousuff
Ranch Hand
Joined: Oct 17, 2007
Posts: 198
|
|
Can i pass a int Array to a method which has variable length argument.For example we have String.format method , where i haev to pass the aregument as array. because i will find the argument length only at the runtime. please see the code below. public String getDisplayMobileNumber(String MobileNumber,PhoneDataObject phoneDO){ int[] numberOfFields = phoneDO.getNumberOfFields(); Object[] phoneNumberSplitUps = new Object[numberOfFields.length]; int pointer = 0; for(int tempCounter = 0 ;tempCounter < numberOfFields.length;tempCounter++){ String temp = MobileNumber.substring(pointer,(pointer + numberOfFields[tempCounter])); /** Moving the Pointer*/ pointer += numberOfFields[tempCounter]; phoneNumberSplitUps[tempCounter] = temp; } return String.format(phoneDO.getDisplayPrintfPattern(),phoneNumberSplitUps); } Any Suggessions ?. thanks for your help
|
My Thoughts : http://passion4java.blogspot.com
Try not to become a man of success but rather to become a man of value.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Have you tried it? The answer is yes you can, but the array needs to be Object[]. Using something like String[] will work but will give you a compiler warning; in that case just cast it to get rid of the warning:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Mohammed Yousuff
Ranch Hand
Joined: Oct 17, 2007
Posts: 198
|
|
|
YES it worked , can you please explain me how it works , can i add more value to this argument ?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Stirng.format uses the technique called varargs. This idea has been in C and C++ for years and since Java 5.0 it finally made it to Java as well. What it means is that whenever you see a parameter with ... behind the type, it means you can enter 0 or more of that type. It must always be the last parameter. Now in Java, this is just a little syntactic sugar. The compiler actually turns it into an array. For example: is turned into this: It just saves you the trouble of creating an Object[] each time.
|
 |
 |
|
|
subject: String.format() - can i pass array ?
|
|
|