java - Vector源码疑惑
高洛峰
高洛峰 2017-04-18 09:04:55
[Java讨论组]

1.在看Vector源码是有2个小知识点比较疑惑
2.疑惑代码如下
/**

    • This implements the unsynchronized semantics of ensureCapacity.

    • Synchronized methods in this class can internally call this

    • method for ensuring capacity without incurring the cost of an

    • extra synchronization.
      *

    • @see #ensureCapacity(int)
      */

    1. void ensureCapacityHelper(int minCapacity) {

         // overflow-conscious code
         if (minCapacity - elementData.length > 0)
             grow(minCapacity);

      }

      /**

      • The maximum size of array to allocate.

      • Some VMs reserve some header words in an array.

      • Attempts to allocate larger arrays may result in

      • OutOfMemoryError: Requested array size exceeds VM limit
        */

    2. static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
      3.疑惑问题点如下:

    问题点1:if (minCapacity - elementData.length > 0),为啥不这样写
    if(minCapacity>elementData.length),效率高在哪?

    问题点2:MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;为啥是减8而不是其他,注释没看明白是啥意思

    高洛峰
    高洛峰

    拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

    全部回复(1)
    阿神

    问题1:溢出的时候会有问题,比如

    int a = Integer.MAX_VALUE + 16;
    int b = Integer.MAX_VALUE;    
    System.out.println(a > b);    
    System.out.println(a - b > 0);

    参考:http://stackoverflow.com/questions/33147339/difference-between-if-a-b-0-and-if-a-b

    问题2:注释已经讲了,有些虚拟机在使用数组的时候会保留一些头信息,所以数组容量不能完全被使用,这里数组是可以建Integer.MAX_VALUE这么大,但是保留了8个容量供虚拟机使用

    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
    php中文网:公益在线php培训,帮助PHP学习者快速成长!
    关注服务号 技术交流群
    PHP中文网订阅号
    每天精选资源文章推送
    PHP中文网APP
    随时随地碎片化学习

    Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号