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

Pea*_*ota 0 java string compare object string-comparison

如果String.length()不能用来比较两个String对象并确定哪个对象更大,那么什么字符串方法会做这样的事情呢?当我运行此代码时,它立即终止.有比较字符串对的方法吗?我在这里使用字符串类的API作为参考: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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Far*_*raz 7

.....
.....
 else if (ObjectOne.length() == ObjectTwo.length()) 
    {
        System.out.println("ObjectOne and ObjectTwo are equal");
    }
Run Code Online (Sandbox Code Playgroud)

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