如何在JAVA中比较两个String对象
问题最近写程序的时候,遇到了需要比较两个 String 对象是否相等的情况,我习惯性的写了形如 String values are compared using ‘==‘,not ‘equals()‘. 也就是说我刚刚那句话应该写成 说明那么,为什么会这样呢? 对于基本数据类型 而对于 我们一般的应用场景主要是要比较两个 String 对象的内容,那就需要使用 equals() 方法。我们可以看一下 java.lang.String 中 equals() 方法的定义,可以看到 equals() 才是在比较两个 String 对象的值。 /** * Compares this string to the specified object. The result is {@code * true} if and only if the argument is not {@code null} and is a {@code * String} object that represents the same sequence of characters as this * object. * * @param anObject * The object to compare this {@code String} against * * @return {@code true} if the given object represents a {@code String} * equivalent to this string,{@code false} otherwise * * @see #compareTo(String) * @see #equalsIgnoreCase(String) */ public Boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; } 还有一个特例的情况,比如 小结当然,如果你知道自己在做什么,就是要利用 == 的这个特性,自然是没有问题的。其他时候用 equals() 方法即可。 Java高级架构狮:专注于Java开发技术的研究与知识分享! ————END———— (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |