What kinds of existing JDK classes could be candidates for value classes, and where might the performance or compatibility tradeoffs make that a bad fit?
Which JDK classes might make good value classes?
Answers
Optional and its primitive variants, such as OptionalInt, are examples mentioned in the value object design material. They represent small pieces of data rather than objects where identity is usually the point.
That makes them useful candidates to look at, though it does not mean every use will automatically get faster or that conversion is guaranteed in a particular release.
Reply to this answer
Map entries are tempting, but the details matter. Map.Entry is an interface, and some entries support changing the value, so treating all entries as immutable value objects would not work. A particular immutable implementation could be a separate question.
Even then, performance is not a simple win. Putting entry data closer together might reduce a cache miss, but larger slots can waste space in a sparse map. Specialized generics and flattening keys could change that calculation. Benchmark the actual layout and workload rather than assuming fewer indirections wins.
Reply to this answer
Enums are a different case. The language design discussed in the source material does not allow a value enum, and an enum already has a finite set of instances. A more compact representation might help in some situations, but alignment and comparison costs complicate the case.
Reply to this answer
MemorySegment is another interesting class to examine, especially if the goal is to find candidates beyond small wrappers. The discussion raises it as a possibility, but does not establish whether it is suitable or what the tradeoffs would be.
Reply to this answer
Add your answer
Answers are reviewed before publication.
8c+addrshift_607:
Anonymous classes are excluded from the candidate definition too, though that alone does not explain all the design reasons behind the restriction.