GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Dynamic array size? and String indicator? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic array size? and String indicator?" Watch "Dynamic array size? and String indicator?" New topic
Author

Dynamic array size? and String indicator?

sahar sa
Ranch Hand

Joined: Jul 06, 2009
Posts: 102
Hi every body,
I have 2 question about arrays:
1) I need to build an array but I dont know the array size initially, So, My question is how can I declare this array? and also how can I add elements to this array?
2)Is this possible to have an array that its indicators are string ? e.g. the normal indicator for an array is int like {0,1,2,3,4} I need something like {A3,A2,A4,A1,A0}.
Thank you in advance,
Sahar.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3833

sahar sa wrote:1) I need to build an array but I dont know the array size initially, So, My question is how can I declare this array?

You have to know the size at some stage: You may declare the array and set it to null initially. But at some stage you have to initialize it with the size.
and also how can I add elements to this array?

Assign the values through it's indexes :


2)Is this possible to have an array that its indicators are string ? e.g. the normal indicator for an array is int like {0,1,2,3,4} I need something like {A3,A2,A4,A1,A0}.

Yes. See above code.
And you also can do like this so you don't have to specify the size explicitly, size is figured out from the number of elements present:


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

You can also look in the Array Tutorial to get these done.


http://muhammadkhojaye.blogspot.com/
Stefan Brandenberger
Greenhorn

Joined: Aug 31, 2009
Posts: 12
What do you mean by "that its indicators are string"? You want to access the array this way?

That won't work.

Maybe you should consider to use a List or a Map.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3833

Yes. If the OP means the index by the "indicators" then that's not possible. I initially thought it's about type of the array.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14194
    
  20

If you need to maintain a list of things but you don't know the size of the list beforehand (at compile time), then you should use a collection class such as ArrayList instead of an array.

See Collections in Sun's Java Tutorials to learn about collection classes.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
GeeCON Prague 2014
 
subject: Dynamic array size? and String indicator?