2

I am reading from K&B about Strings. For some extra know how, i was reading tutorial from Oracle. I am copying the source code from Oracle.

public class StringDemo {  
    public static void main(String[] args) {  
        String palindrome = "Dot saw I was Tod";  
        int len = palindrome.length();  
        char[] tempCharArray = new char[len];  
        char[] charArray = new char[len];  

        // put original string in an   
        // array of chars  
        for (int i = 0; i < len; i++) {  
            tempCharArray[i] =   
                palindrome.charAt(i);  
        }   

        // reverse array of chars  
        for (int j = 0; j < len; j++) {  
            charArray[j] =  
                tempCharArray[len - 1 - j];  
        }  

        String reversePalindrome =  
            new String(charArray);  
        System.out.println(reversePalindrome);  

        //Testing getChars method //1  
        palindrome.getChars(0, len, tempCharArray, 1);  
        String tempString = new String(tempCharArray);  
        System.out.println(tempString);  
    }  
}

I added point-1 in source code. I was understaning getChars method. When i run it, this program give me ArrayIndexOutOfBoundsException. Here is what i read in String docs.

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Throws: IndexOutOfBoundsException - If any of the following is true: srcBegin is negative. srcBegin is greater than srcEnd srcEnd is greater than the length of this string dstBegin is negative dstBegin+(srcEnd-srcBegin) is larger than dst.length

What is the destBegin? What offset, the documentation is talking about. 1 is a valid offset in destination array. Please help me solve this confusion.

Thanks.

4

3 回答 3

1

如文档中所写

字符被复制到 dst 的子数组中,从索引 dstBegin 开始,到索引结束:

 dstbegin + (srcEnd-srcBegin) - 1

所以在你的情况下

1 + (len - 0) -1 = 长度

请注意,这是结束索引- 所以你的结束索引是len,但在你的数组中,最后一个索引是len -1

于 2014-09-22T17:35:23.020 回答
1

你得到一个,IndexOutOfBoundsException因为你已经用完了目标数组中的空间tempCharArray,它是长度len。要复制数组,getChars请在数组开头的目标数组中开始,在 index 处0

palindrome.getChars(0, len, tempCharArray, 0);  
于 2014-09-22T17:32:00.597 回答
0

tempCHARArray 的长度与回文的长度相同。您正在尝试从索引 1 开始复制回文数组。试试这个并重新运行或从 0 开始索引 - >

char[] tempCharArray = new char[len + 1]; 
于 2014-09-22T17:34:13.143 回答