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 */ }

 

posted @ 2012-11-05 14:26  爱我所艾  阅读(229)  评论(0编辑  收藏  举报