Why is java.lang.Integer.valueOf a flyweight pattern?
Why is java.lang.Integer.valueOf a flyweight pattern? I tried to find开发者_如何转开发 the reason but wasn't able to.
If we look at the source for valueOf
, we can get a hint:
Source of java.lang.Integer lines 638-643:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
It looks like the Integer class maintains a cache of Integer objects for common values. Rather than make a new one every time somebody asks for valueOf
, it just returns a reference to one that already exists. Therefore, if you call Integer.valueOf(1)
multiple times, you'll end up getting the same object back every time (not just equivalent objects).
This sounds like you have been asked to solve an exercise.
If you call the method twice with the same argument, it may return the same object thereby limiting the memory usage. This fits the definition of flyweight pattern.
精彩评论