Swap two strings in Java, by passing them to a utility function, but without returning objects or using wrapper classes

前端 未结 9 2245
既然无缘
既然无缘 2020-12-16 20:31

I am trying to swap two strings in Java. I never really understood \"strings are immutable\". I understand it in theory, but I never came across it in practice.

Also

9条回答
  •  暖寄归人
    2020-12-16 21:18

    The following code is a NoGo, never implement this anti pattern, never ever ever ever change private final internals on immutable objects. Don't blame me for showing this hack, blame Oracle's jvm for not disallowing it.

    But, if one day you find some code where this works:

     String a = "Hello";
     String b = "World";
     String c = "World";
     swap(a,b);
     System.out.printf("%s %s%n", a,b);  // prints: World Hello !!
    
     System.out.println(c);  // Side effect: prints "Hello" instead of "World"....
    

    the implementation of swap could look like this: (read on your own risk, I warned you!)

     private void swap(String a, String b) {
       try {
         Field value = String.class.get("value");
         value.setAccessible(true);    // this should be forbidden!!
    
         char[] temp = value.get(a);
         value.set(a, value.get(b));
         value.set(b, temp);           // Aaargh, please forgive me
       } catch(Exception e) {
         e.printStackTrace(e);
       }
     }
    

提交回复
热议问题