前言:本博文将涉及的Java的自动装箱和自动拆箱,可以参考 这篇文章 和 官方教程 ,这里不再赘述。

 

首先,先看一个小程序:

public class Main {
    
    public static void main(String[] args){
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        System.out.println(i1 == i2);
        
        Integer i3 = 1;
        Integer i4 = 1;
        System.out.println(i3 == i4);
        
        Integer i5 = 200;
        Integer i6 = 200;
        System.out.println(i5 == i6);
    }
}

 

上面的程序会依次输出false 、true、false。

 第一个输出语句应该比较好理解,就是创建了不同的对象。但是第二跟第三个输出语句估计很多人就很难理解了。

要解释这个问题,需要从缓存说起。

 

缓存

  缓存是软件设计模式中一个非常有用的模式,缓存的实现方式有很多,不同方式可能存在性能上的差别。下面给出一个用数组实现的实例:

  (1)缓存类Cache_test

/*
 * <p>
 * 该对象使用数组实现了缓存,也就是,
 * 每一次使用valueOf()创建新对象时,系统将会确认缓存中是否已经存在相应的对象(即data相等)。
 * 假如存在,则直接返回缓存已存在的对象;
 * 假如不存在,则创建一个新对象,存储到缓存中,并返回新创建的对象。
 * </p>
 * 
 * @author Harvin.
 * @version 1.0
 */
public class Cache_test {
    //需要存储的数据
    private final String data;
    
    public Cache_test(String data){
        this.data = data;
    }
    public String get_data(){
        return this.data;
    }
    @Override
    //直接判断是否是指向同一个对象
    public boolean equals(Object obj){
        if (this == obj) {
            return true;
        }
        return false;
    }
    
    
    //定义缓存的大小
    private final static int MAX_SIZE = 10;
    //使用数组来存储缓存
    private static Cache_test[] cache
    = new Cache_test[MAX_SIZE];
    //定义当前缓存存储的位置
    private static int pos = 0;
    
    /* 判断是否已经缓存了包含该data对象的Cache_test对象,
     * 如果存在,则直接返回;
     * 如果不存在,则直接创建后再将其返回
     */
    public static Cache_test valueOf(String data){
        for (int i = 0; i < MAX_SIZE; i++) {
            if (cache[i] != null
                    && cache[i].get_data().equals(data)) {
                return cache[i];
            }
        }
        if(MAX_SIZE == pos){
            cache[0]    = new Cache_test(data);
            pos            = 1;
        }else{
            cache[pos]    = new Cache_test(data);
        }
        return cache[pos++];
    }
}
Cache_test

相关文章:

  • 2022-12-23
  • 2021-06-16
  • 2021-08-04
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2022-12-23
  • 2021-11-19
猜你喜欢
  • 2021-09-09
  • 2022-12-23
  • 2021-06-28
  • 2021-11-20
  • 2022-12-23
  • 2021-06-01
相关资源
相似解决方案