Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
59 views
in Technique[技术] by (71.8m points)

java - Why are values in the OpenJDK implementation of HashMap (and other classes) initialized using bitshifts?

I was looking at OpenJDK's implementation of HashMap and stumbled upon this line of code where the default initial capacity is set:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

Why is a bitshift used here instead of just initializing DEFAULT_INITIAL_CAPACITY with 16? I've looked at other classes like Arrays and there, too, a value is initialized with a bitshift:

private static final int MIN_ARRAY_SORT_GRAN = 1 << 13;

Is it a conventional thing or is it more important for someone working with these implementations to know which binary number the values are instead of the decimal representation?

question from:https://stackoverflow.com/questions/65846183/why-are-values-in-the-openjdk-implementation-of-hashmap-and-other-classes-init

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because sometimes it's easier to reason with number of bits, rather than numerical ranges. In the case of HashMap, however, another reason is that you need to do hash % numberOfBuckets, the modulo operation is expensive, so to fasten up one can use a power of two, then modulo may be replaced with logical AND - it'll do the same, but works that way only for powers of two. The Arrays case - may be similar reasons.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...