在java里用clojure的immutable data collection, 比如persistentHashMap. 这样用好处是immutable?具体来说immutable能解决多线程的问题? compound operation还是得自己保护吧? package persistent; import clojure.lang.IPersistentMap; import clojure.lang.IPersistentSet; import clojure.lang.IPersistentVector; import clojure.lang.PersistentHashMap; import clojure.lang.PersistentHashSet; import clojure.lang.PersistentVector; public class PersistentTest { public static void main(String[] args) { IPersistentMap m = PersistentHashMap.create("abc", "xyz"); m = m.assoc(1, 4); // add a new key/value pair m = m.assoc("key", "value"); m = m.without("abc"); // remove key "abc" System.out.println(m);
IPersistentVector v = PersistentVector.create(1, 2, 3); v = v.assocN(0, "a string"); // change index 0 v = v.cons("should be last"); // add a string at the end System.out.println(v);
IPersistentSet s = PersistentHashSet.create("a", "b", "c"); s = (IPersistentSet) s.cons("d"); // add d to the set s = (IPersistentSet) ((IPersistentMap) s).without("a"); // remove an element s.contains("g"); // should return false System.out.println(s); } }