• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding array  RSS feed

 
santhosh kumar vk
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have one doubt that is we have declared string array size 10 now we have to insert 15 different string in that array with out change the size of the array can you tell me how to put value into array string.

for example

String a[]=new String[10];


A
B
C
D
E
F
G
H
I
J
K
l
M
N
O

into that array.
Thanking You




 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need to put 15 strings into an array that can only store 10 strings without being allowed to replace it, you have two options:
1) drop 5 of the strings
2) merge the strings somehow

Either way, you need to find an algorithm to decide which strings to drop, or how to merge strings.
 
S Shehab
Ranch Hand
Posts: 492
Android Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DO you must use Array?
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create a new array with desired size and copy strings from the old array to the new one.
There is an utility function Arrays.copyOf(array, newSize) that does this job:
http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28T[],%20int%29

But if your array will grow, then a better solution is to use ArrayList instead of manually resizing the array.
 
S Shehab
Ranch Hand
Posts: 492
Android Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ireneusz Kordal wrote:You can create a new array with desired size and copy strings from the old array to the new one.
There is an utility function Arrays.copyOf(array, newSize) that does this job:
http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28T[],%20int%29

But if your array will grow, then a better solution is to use ArrayList instead of manually resizing the array.


As Ireneusz said , use ArrayList better in the resizing issue.. beacause it's size will be dynamic ...
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't believe creating a new array or using an arraylist solves this particular problem, The issue is inserting 15 strings in a 10 element array without changing the size. Rob's suggestion seems to be the easiest to me.

-Hunter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!