Generic InternPool in Java?

后端 未结 6 1159
天涯浪人
天涯浪人 2021-01-12 01:04

How would I write a generic InternPool in Java? Does it need a Internable interface?

String in Java has interning cap

6条回答
  •  走了就别回头了
    2021-01-12 01:44

    Just a quick caveat:

    It has not been explicitly mentioned above, but it should be obvious that the objects being interned must be of an immutable type.

    On a second note: You don't need to use another weak reference to the object as the value in the map, a reference to a static would suffice if you just rely on the map's keyset for the data. For example, declare:

    WeakHashMap
    

    And insert pairs as:

    pool.put (object, Boolean.TRUE);
    

    Which is a minor saving of a WeakReference instance (if you can't reuse the one used for the key).

    ...or create a WeakSet class, as @PeterVerhas has done with his WeakPool.

提交回复
热议问题