我知道在java中我们可以使用.equals方法来比较两个字符串是否相等。但是,如果2个字符串非常长,如下所示:
String s1 = "t was her sister Josephine who told her, in broken sentences; veiled hints that revealed in half concealing. Her husband's friend Richards was there, too, near her. It was he who had been in the newspaper office when intelligence of the railroad disaster was received, with Brently Mallard's name leading the"
String s2 = "t was her sister Josephine who told her, in broken sentences; veiled hints that revealed in half concealing. Her husband's friend Richards was there, too, near her. It was he who had been in the newspaper office when intelligence of the railroad disaster was received, with Brently Mallard's name leading the"
if s1.equals(s2) return true;
如果被比较的字符串很大,那么.equals会不会有效?有什么限制吗?我需要知道比较2个长串的最佳方法是什么。
答案 0 :(得分:3)
如果被比较的字符串很大,.equals仍会有效吗?
是
有任何限制吗?
仅限Java字符串的最大大小(2 ^ 31 - 1个字符)或堆大小限制。
(但是那些字符串本身的大小限制不在equals
方法上。)
我需要知道比较2个长串的最佳方法是什么。
使用String.equals(Object)
如果您有多个字符串和/或想要多次比较它们,那么将String.hashCode()
与String.equals
结合使用可能可以提高效果。 (这取决于被比较的字符串的性质;即对的概率相等而“几乎”相等。)
答案 1 :(得分:0)
是的,它会起作用。可能需要一些时间(很可能甚至不会花一秒钟)。但是,不要低估现代设备的编译能力。它会在一眨眼之间进行比较。