Long与Arrays的使用注意

130 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

Long与Arrays的使用注意

Long的缓存机制

这个点应该是很多人忽略的问题,其实Long内部做了一个缓存,缓存的范围是-128 到 127,以下为源代码:

    private static class LongCache {
        static final Long[] cache = new Long[256];

        private LongCache() {
        }

        static {
            for(int i = 0; i < cache.length; ++i) {
                cache[i] = new Long((long)(i - 128));
            }

        }
    }

LongCache为Long的静态内部类,其中有一个静态初始化方法,类在加载时,则会创建缓存。根据循环次数可以看到,缓存的数是-128 到 127。

在使用的时候,新建Long对象也不一定会用到缓存,例如:Long.valueOf()就会使用到缓存,而parseLong则不会用到缓存。

Long的比较

如果要比较两个Long对象是否相等,使用的方法是equals()。

如果要比较两个Long对象的数值是否相等,不是使用==,==只是判断两个变量指向的内存地址是否相同。需要使用Long.longValue(),转换为long类型,再进行大小比较。

Arrays-排序

Arrays中主要用于排序的方法是Arrays.sort(),入参可以为多种类型,包括:int、long、double等,也可以传入自定义类型的数组,Demo代码:

class Student{
    private String name;
    
    //构造方法略
    
    //get、set方法略

}

public void testSort(){
  List<Student> list = Lists.newArrayList(
      new Student("小明"),
      new Student("小红"),
      new Student("小吖"),
      new Student("小天")
  );
  Student[] array = new Student[list.size()];
  list.toArray(array);

  System.out.println("排序前:" JSON.toJSONString(array));
  Arrays.sort(array, Comparator.comparing(Student::getName));
  System.out.println("排序后:" JSON.toJSONString(array));

}

此处虽然使用的String类型的name排序,但是现象可以看出排序的目的已经达到了,也可实现Comparatable重写compare方法进行排序。

Arrays-二分查找

Arrays.binarySearch()可以用于快速从数组中查找出对应的值。 入参类型非常多,如 byte、int、long 各种类型的数组。还是使用刚刚的例子:

public void testSort(){
  List<Student> list = Lists.newArrayList(
      new Student("小明"),
      new Student("小红"),
      new Student("小吖"),
      new Student("小天")
  );
  Student[] array = new Student[list.size()];
  list.toArray(array);

  System.out.println("排序前:" JSON.toJSONString(array));
  Arrays.sort(array, Comparator.comparing(Student::getName));
  System.out.println("排序后:" JSON.toJSONString(array));
  int index = Arrays.binarySearch(array, new Student("小吖"),
                    Comparator.comparing(Student::getName));
  if(index<0){
      //未找到
  }
  System.out.println("搜索结果::" JSON.toJSONString(array[index]));

}
  1. 如果被搜索的数组是无序的,一定要先排序,否则二分搜索很有可能搜索不到,我们 demo 里面也先对数组进行了排序;
  2. 搜索方法返回的是数组的下标值。如果搜索不到,返回的下标值就会是负数,这时我们需要判断一下正负。如果是负数,还从数组中获取数据的话,会报数组越界的错误。demo 中对这种情况进行了判断,如果是负数,可以抛出异常。