Hi
We want to make my class immutable like as String class in java How can make it .
What is immutable class How it will created in java ?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Satyapriya NayakRank #47 · 31.5K reputationPosted Mar 18, 2012, 12:00 AM EDT
import java.lang.reflect.Field; public class MutableString { public static void main(String[] argv) { String s = "Immutable"; String t = "Notreally"; mutate(s, t); StdOut.println(t); // strings are interned so this doesn't print "Immutable" StdOut.println("Immutable"); } // change the first min(|s|, |t|) characters of s to t public static void mutate(String s, String t) { try { Field val = String.class.getDeclaredField("value"); Field off = String.class.getDeclaredField("offset"); val.setAccessible(true); off.setAccessible(true); int offset = off.getInt(s); char[] value = (char[]) val.get(s); for (int i = 0; i Math.min(s.length(), t.length()); i++) value[offset + i] = t.charAt(i); } catch (Exception e) { e.printStackTrace(); } } }Please refer the below link
http://algs4.cs.princeton.edu/12oop/MutableString.java.html
Thanks
VulpesRank #55 · 29.2K reputationPosted Mar 18, 2012, 4:37 AM EDT
http://www.javapractices.com/topic/TopicAction.do?Id=29