p.equals(w) 总是成真。为什么?
import java.io.*;
import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0){
String k=s.next();
StringBuffer p=new StringBuffer(k);
int c=0;
StringBuffer w=p.reverse();
if(p.equals(w)){
System.out.print(p.equals(w));
for(int i=0;i<p.length();i++)
{
if(p.charAt(i)=='1'||p.charAt(i)=='0'||p.charAt(i)=='8') { c++;}
}
}
if(c==p.length())System.out.println("YES");
else System.out.println("NO");
}
}
}
最佳答案
public synchronized StringBuffer reverse() {
super.reverse();
return this;
}
Reverse 将反转 String 并将其设置在同一个 StringBuffer 对象中。所以它总是一样的。
所以
p.reverse();
做的和说的一样
p = p.reverse();
然后如果你这样做
StringBuffer w=p.reverse();
p
和 w
将打印到同一个对象。不用说 equals()
将返回 true
。
您可以在 StringBuffer
的反向操作之前和之后存储字符串对象,然后对它们使用 equals()。 toString()
返回新的字符串对象。
public synchronized String toString() {
return new String(value, 0, count);
}
关于java - 为什么使用 StringBuffer.reverse 后 equals() 为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312853/