java string isempty,java – String.isEmpty()和String.equals(“”)之间的区别

本文探讨了在Java中检查字符串是否为空的最佳实践。通过对比isEmpty()和equals(“”)两种方法,详细分析了它们的实现原理及性能差异。推荐在不担心null值的情况下使用isEmpty()方法。

我认为isEmpty()更有效率。然而,智能编译器可能会优化equals(“”)调用。从

OpenJDK source:

671 public boolean isEmpty() {

672 return count == 0;

673 }

1013 public boolean equals(Object anObject) {

1014 if (this == anObject) {

1015 return true;

1016 }

1017 if (anObject instanceof String) {

1018 String anotherString = (String)anObject;

1019 int n = count;

1020 if (n == anotherString.count) {

1021 char v1[] = value;

1022 char v2[] = anotherString.value;

1023 int i = offset;

1024 int j = anotherString.offset;

1025 while (n-- != 0) {

1026 if (v1[i++] != v2[j++])

1027 return false;

1028 }

1029 return true;

1030 }

1031 }

1032 return false;

1033 }

还有answer here关于是否使用str.isEmpty()或“”.equals(str)是现成的:

The main benefit of "".equals(s) is you don’t need the null check (equals will check its argument and return false if it’s null), which you seem to not care about. If you’re not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you’re checking, you care whether or not s is empty, not whether it equals the empty string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值