• Post Reply Bookmark Topic Watch Topic
  • New Topic

Dynamic String Array Decelaration  RSS feed

 
Azrael Noor
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every time i have to give size for dynamic decleration like

String sa[] = new String[val];

i want to use unlimited size of string using dynamic string array deceleration instead of using any other data structures.

i found that When i give no size it throw null point exception, when i give size it gives array out of bond.
so i have to take care of both things which is not allowing me to finish my work.

Kindly tell me isthere any decelaration so that i could dynamically increase space ?









 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays have a fixed length in Java. If you want the size to be dynamic, you need to use a List object (such as an ArrayList).
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are given a size when you declare them. There is no getting around that. It's just how they work.

there are other, different data structures that are similar to arrays that grow if you need them to do so. Why must it be an array?

 
Azrael Noor
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but i have done lot of work and not in mood of shifting to some other datastructure
well i will sort it out thanks for increasing my information part.
 
James Elsey
Ranch Hand
Posts: 228
Android IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Couple of suggestions, not sure how valid/if they would actually work

1. Create an array bigger than what you need, so you will always have spare "spaces"
2. if you want to increase the size of an array, create a new one with +1 size, and copy items across

Both of those are incredibly poor, only suggesting since you're not keen on implementing one of the List flavours

Definately have a read of List, particulary the ArrayList it may take you time to re-code some stuff, but it'll pay off in the long run
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Azrael Noor wrote:but i have done lot of work and not in mood of shifting to some other datastructure
well i will sort it out thanks for increasing my information part.

Welcome to the world of programming.

I'm not trying to be flip, or discount your pain, but you have (hopefully) learned an important lesson here. If you had spent a little more time up front, on the design, you may not be in this situation now.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!