java 如何使用 .equals() 方法比较两个 StringBuffer 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17110518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:02:01  来源:igfitidea点击:

How to compare two StringBuffer Objects using .equals() method?

javastringtostringstringbufferobject-to-string

提问by Praveen Kumar

The following code did not work. Can anyone tell me what's wrong with the following code. Logically it should work...

以下代码不起作用。谁能告诉我下面的代码有什么问题。从逻辑上讲它应该工作......

package assignments;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IsPalindrome {
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(
                                      new InputStreamReader(System.in));
    System.out.println("Enter a Word:");
    StringBuffer sb1 = new StringBuffer(br.readLine());
    StringBuffer sb2 = new StringBuffer(sb1);
    sb1.reverse();

    if(sb2.equals(sb1))
        System.out.println("Palindrome");
    else
        System.out.println("Not a Palindrome");
}
}

回答by darijan

Try

尝试

sb1.toString().equals(sb2.toString());

because StringBuffer#toStringmethod returns the String value of the data stored inside the buffer:

因为StringBuffer#toString方法返回存储在缓冲区内的数据的 String 值:

Returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.

返回表示此序列中数据的字符串。分配并初始化一个新的 String 对象,以包含该对象当前表示的字符序列。然后返回此字符串。对该序列的后续更改不会影响字符串的内容。

回答by Dulanga

In StringBuffer class equalsmethod is not overriden as in Stringclass. In StringBufferit just looks whether the references are the same. Therefore you first need to convert that to a String and then use equals method.

在 StringBuffer 类中的equals方法不像在String类中那样被覆盖。在StringBuffer它只是看起来的引用是否是相同的。因此,您首先需要将其转换为字符串,然后使用 equals 方法。

So Try

所以试试

sb1.toString().equals(sb2.toString());

回答by Peter Lawrey

You can write

你可以写

System.out.println("Enter a line:");
String line = br.readLine().replace(" ", ""); // palindromes can have spaces
String reverse = new StringBuilder(sb1).reverse().toString();

if(line.equals(reverse))
    System.out.print("Not a ");
System.out.println("Palindrome");