Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic array size? and String indicator?

 
sahar sa
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also look in the Array Tutorial to get these done.
 
Stefan Brandenberger
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic