小编Pea*_*ota的帖子

为什么此代码会产生IndexOutOfBoundsException?

有人可以解释这个问题......

为什么:

String letters[] = { "A", "B", "C" };
ArrayList<String> list = new ArrayList<String>(3);

for(int i=2 ; i >= 0 ; i--)
    list.set(i,letters[i]);


for(int i=0 ; i < list.size() ; i++)
    System.out.print(list.get(i));
Run Code Online (Sandbox Code Playgroud)

制作: IndexOutOfBoundsException

java string for-loop arraylist indexoutofboundsexception

2
推荐指数
1
解决办法
35
查看次数

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

如果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)

java string compare object string-comparison

0
推荐指数
1
解决办法
90
查看次数