可以使用“String.length()”来查看两个 String 对象中哪个更大吗?

Can `String.length()` be used to see which of two String objects is larger?

如果String.length()不能用来比较两个String对象并判断哪个对象更大,那么什么string方法会做这样的事情?当我 运行 这段代码时,它会立即终止。有没有比较字符串对的方法?我在这里使用 API 作为字符串 class 的参考:https://docs.oracle.com/javase/6/docs/api/java/lang/String.html

public class ThingsComparer {

    public static void main(String[] args) {

        String ObjectOne = new String("One");
        String ObjectTwo = new String("Two");

        if (ObjectOne.length() > ObjectTwo.length())
        {
            System.out.println("ObjectOne is larger");
        }
        else if (ObjectOne.length() < ObjectTwo.length())
        {
            System.out.println("ObjectTwo is larger");
        }
        else if (ObjectOne.equals(ObjectTwo)) 
        {
            System.out.println("ObjectOne and ObjectTwo are equal");
        }
    }
}
.....
.....
 else if (ObjectOne.length() == ObjectTwo.length()) 
    {
        System.out.println("ObjectOne and ObjectTwo are equal");
    }

此外,根据 Thilo 的说法,在您尝试寻找大于和小于条件之后,您根本不需要 else if (ObjectOne.length() == ObjectTwo.length())。第三个条件是什么?这是平等的。

@Peanutcalota

以上代码运行良好。您没有得到任何输出的原因是 2 个对象 ObjectOneObjectTwo 具有不同的字符串并且长度相等。

所以第一个和第二个条件将不起作用,因为它们的长度相同。

最后一个条件不成立,因为两个字符串不同。

ObjectOne.equals(ObjectTwo) 仅当它们具有相同的字符串时才有效。

而且我试过 运行 这个程序,它运行良好。

试一试。