Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string[] modification

 
mark I thomas
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic