i have tried to assign directly and by creating new instance also. it is assigning values fine.but if i try to modify the normal string array,static string array is also modifying.can anyone help on this
-
2Can you share your code, please?Konstantin Yovkov– Konstantin Yovkov2015-08-20 06:31:09 +00:00Commented Aug 20, 2015 at 6:31
-
defensive copy. create a new array with the same values, instead of a shared reference.Stultuske– Stultuske2015-08-20 06:31:32 +00:00Commented Aug 20, 2015 at 6:31
-
i think a deep copy will help... stackoverflow.com/questions/1564832/…thomas– thomas2015-08-20 06:35:59 +00:00Commented Aug 20, 2015 at 6:35
Add a comment
|
2 Answers
If you create a new string array, it wont share the reference.
Example with String:
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
More info: https://www3.ntu.edu.sg/home/ehchua/programming/java/J3d_String.html
Comments
Use Arrays.copyOf which not only copy elements, but also creates a new array.
See the below code, it solves your problem:-
static String[] array=new String[]{"1","2"};
public static void main(String[] args) {
String[] array2=Arrays.copyOf(array, array.length);
System.out.println("Printing array2:-");
for(String elem:array2){
System.out.print(elem+"|");
}
System.out.println("\nPrinting array:-");
array[0]="4";
for(String elem:array){
System.out.print(elem+"|");
}
System.out.println("\nPrinting array2:-");
for(String elem:array2){
System.out.print(elem+"|");
}
}
Output:-
Printing array2:-
1|2|
Printing array:-
4|2|
Printing array2:-
1|2|
