aspose file tools*
The moose likes Beginning Java and the fly likes string[] modification Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "string[] modification" Watch "string[] modification" New topic
Author

string[] modification

mark I thomas
Ranch Hand

Joined: Apr 07, 2008
Posts: 86
I have a hashMap. Its key is some string object, the value is a fixed size string array. Initially I need all the elements in the string[] be null or "" (empty string). Then I want to retrieve a value from a hashmap and modify that string array. Then I want to retrieve the modified string[] which is the value in the hashmap. Here is my code --



Question ---

1. String[] a = (String[])hm.get("a"); In this line I cast the retrieved object into string[] and assign it to a new string[] object "a", then I modify "a" array. Does it just modify the new array "a" or does it actually modify the array object that is stored as the value
for key "a" ? My output shows it works fine but I want to understand why.

2. code "new string[3]" automatically default the elements to null for this array. Is ther fast way to create a string array with "" (empty string) as default value ? The simple the better. How ?



>
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

1. The get method will return you the reference of the original array, so variable "a" is the same object as the one you created with "new String[3]".

2. You could use "new String[]{"","",""}". It's fine with only three elements, but it's not good with many more elements. One other way I can think of is by calling the Arrays#fill method.


[My Blog]
All roads lead to JavaRanch
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: string[] modification