封装类型以Long为例,基础类型以long为例
1 比较equals与==

@Test
public void testEquals() {
    Long l1 = 10000L;
    long l2 = 10000l;
    Long l3 = 10000l;
    // 封装类型与基础类型==比较的时候,封装类型会自动转成基本类型做比较
    System.out.println(l1 == l2); // true
    System.out.println(l1 == l3); // false
    System.out.println(l1.longValue() == l3.longValue()); // true
}

总结1:如果使用==号比较,需要把1侧的类型转成基础类型

2 速度equals与==哪个更快呢?

@Test
public void testFast() {
    // string的equals和long的equals,哪个更快
    int N = 1000000;
    long[] l1 = new long[N];
    long[] l2 = new long[N];
    Long[] data1 = new Long[N];
    Long[] data2 = new Long[N];
    String[] str1 = new String[N];
    String[] str2 = new String[N];
    long j = 0;
    for (int i = 0; i < N; i++) {
        data1[i] = j;
        data2[i] = j;
        str1[i] = String.valueOf(j);
        str2[i] = String.valueOf(j++);
    }

    compareL(l1, l2, N); // 10
    compareLong1(data1, data2, N); // 100
    compareLong(data1, data2, N); // 600
    // 总结:Long1.longValue()==Long2.longValue() 比 Long1.equals(Long2) 更快
    compareStr(str1, str2, N); // 1000
}

public void compareL(long[] data1, long[] data2, int N) {
    long startL = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < N; j++) {
            if (data1[j] == (data2[j])) {
            }
        }
    }
    long endL = System.currentTimeMillis();
    System.out.println("compareL tasks times :" + (endL - startL));
}

public void compareLong(Long[] data1, Long[] data2, int N) {
    long startL = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < N; j++) {
            if (data1[j].equals(data2[j])) {
            }
        }
    }
    long endL = System.currentTimeMillis();
    System.out.println("compareLong tasks times :" + (endL - startL));
}

public void compareLong1(Long[] data1, Long[] data2, int N) {
    long startL = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < N; j++) {
            if (data1[j].longValue() == data2[j].longValue()) {
            }
        }
    }
    long endL = System.currentTimeMillis();
    System.out.println("compareLong tasks times :" + (endL - startL));
}

public void compareStr(String[] data1, String[] data2, int N) {
    long startL = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < N; j++) {
            if (data1[j].equals(data2[j])) {
            }
        }
    }
    long endL = System.currentTimeMillis();
    System.out.println("compareStr tasks times :" + (endL - startL));
}

总结2:
通过compareLong1和compareLong对比,可以发现在保证数据正确的前提下,==比equals的速度要快。结合总结1,我们可以在封装类型比较多时候,使用l1.longValue() == l2.longValue();


求平安
15 声望0 粉丝

家人平平安安。


« 上一篇
java8 map新特性