zoukankan      html  css  js  c++  java
  • java的Equal

    JDK中Equal的源码如下所示: 

     public boolean equals(Object anObject) {
    	if (this == anObject) {
    	    return true;
    	}
    	if (anObject instanceof String) {
    	    String anotherString = (String)anObject;
    	    int n = count;
    	    if (n == anotherString.count) {
    		char v1[] = value;
    		char v2[] = anotherString.value;
    		int i = offset;
    		int j = anotherString.offset;
    		while (n-- != 0) {
    		    if (v1[i++] != v2[j++])
    			return false;
    		}
    		return true;
    	    }
    	}
    	return false;
        }
    

    通过如下的例子验证:

      第一次走到this == anObject返回ture,第二次走完全部,第三次走到if (n == anotherString.count)返回false,所以时间为time1 = 63 time2 = 391 time3 = 78


    public void StringEqual() {
    		String a = "HelloWorld";
    		String b = "HelloWorld";
    		long start1 = System.currentTimeMillis(); // <+++ Start timing
    		for (int i = 0; i < 10000000; i++)
    			a.equals(b);
    		long stop1 = System.currentTimeMillis(); // <+++ Stop timing
    		System.out.println(" time1 = " + (stop1 - start1));//走到this == anObject返回ture
    String c = "HelloWorld"; String d = "HelloWorlD"; long start2 = System.currentTimeMillis(); // <+++ Start timing for (int i = 0; i < 10000000; i++) c.equals(d); long stop2 = System.currentTimeMillis(); // <+++ Stop timing System.out.println(" time2 = " + (stop2 - start2));//走完全部 String e = "HelloWorld"; String f = "HelloWorld1"; long start3 = System.currentTimeMillis(); // <+++ Start timing for (int i = 0; i < 10000000; i++) e.equals(f); long stop3 = System.currentTimeMillis(); // <+++ Stop timing System.out.println(" time3 = " + (stop3 - start3));//走到if (n == anotherString.count)返回false
    /* * System.out.println(); time1 = 63 time2 = 391 time3 = 78 */ }
  • 相关阅读:
    ECS:Systems
    ECS:Components
    ECS:Entitias
    对List遍历过程中添加和删除的思考
    SpringBoot 推荐博客
    理解和解决Java并发修改异常ConcurrentModificationException(转载)
    我对CopyOnWrite的思考
    最简日志打印规范(推荐,转载)
    为什么不应该使用Zookeeper做服务发现?(转载)
    浏览器允许跨域设置(不用于生产环境,开发用)
  • 原文地址:https://www.cnblogs.com/wangchy0927/p/2755077.html
Copyright © 2011-2022 走看看