Results 1 to 5 of 5
Thread: creating array at runtime
- 11-08-2007, 09:14 AM #1
Member
- Join Date
- Nov 2007
- Posts
- 97
- Rep Power
- 0
creating array at runtime
Hi,
I want to create an array at run time. I am not sure about its size when coding. I take an input from user through console and then want to create the array of that size.
In the example above, I mentioned the size which is fine. I just want to know if size can be given later?Java Code:int[] array = new int [5];
Is this possible? How?
Thanks.
- 11-08-2007, 09:37 AM #2
if size can be given later
No. You have to instantiate an array with a size. You can change the size later by making a new array of the same type at a different size and copying the elements of the old array into it - actually assigning the new elements the value of the old elements. The System.arraycopy method is useful for this.
- 11-08-2007, 12:54 PM #3
Member
- Join Date
- Jun 2007
- Location
- Colombo, Sri Lanka
- Posts
- 32
- Rep Power
- 0
You could do something like this.
Here size is an integer variable with some value. If the value of 'size' is determined at the runtime then your array size will be determined at runtime.Java Code:int[] array = new int[size];
Regards,
Hiranya
- 11-08-2007, 09:13 PM #4
Member
- Join Date
- Nov 2007
- Posts
- 97
- Rep Power
- 0
Thanks. Its helps.
- 11-08-2007, 10:06 PM #5
I just want to know if size can be given later?
You can re/instantiate the array at any time.
Java Code:class Pseudo { int[] sizes; // declaration String[] ids = new String[0]; // declaration and instantiation; void someMethod() { // Instantiate the sizes array declared as a member variable. // Java assigns each element the default value of zero. sizes = new int[16]; // Instantiate the ids array declared and insantiated as a // (zero-length array) member variable. // Each element of this array is null. ids = new String[4]; } }
Similar Threads
-
Creating an array of nonprimitive objects
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:46 PM -
Need help with creating array of type object
By riz618 in forum New To JavaReplies: 3Last Post: 01-29-2008, 06:14 AM -
Creating Array of LinkedList
By sasikumardr in forum New To JavaReplies: 1Last Post: 12-11-2007, 10:25 AM -
How to initialize array at runtime
By Java Tip in forum Java TipReplies: 0Last Post: 11-09-2007, 03:47 PM -
Initialize array at runtime
By javaplus in forum Java TipReplies: 2Last Post: 11-09-2007, 11:44 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks