【问题标题】:String getChars() method confusionString getChars() 方法混淆
【发布时间】:2014-09-22 17:26:12
【问题描述】:

我正在阅读关于字符串的 K&B。对于一些额外的知识,我正在阅读 Oracle 的教程。我正在从 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);  
    }  
}

我在源代码中添加了第 1 点。我正在理解 getChars 方法。当我运行它时,这个程序给了我 ArrayIndexOutOfBoundsException。这是我在字符串文档中读到的内容。

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

抛出:IndexOutOfBoundsException - 如果以下任何一项为真: srcBegin 是负数。 srcBegin 大于 srcEnd srcEnd 是 大于这个字符串的长度 dstBegin 是负数 dstBegin+(srcEnd-sr​​cBegin) 大于 dst.length

destBegin 是什么?什么偏移量,文档正在谈论。 1 是目标数组中的有效偏移量。请帮我解决这个困惑。

谢谢。

【问题讨论】:

  • 您可以在问题中添加源字符串和目标字符串吗?这可能有助于我们澄清为什么它会越界。
  • 不确定是什么问题... 1 是一个有效的偏移量
  • @JasonD 源字符串包含在程序中。
  • 错过了,它在回文中:)

标签: java ocpjp


【解决方案1】:

如documentation中所写

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

 dstbegin + (srcEnd-srcBegin) - 1

所以在你的情况下是

1 + (len - 0) -1 = len

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

【讨论】:

  • 这意味着,目标长度在运行时由 JVM 自己使用公式 dstbegin + (srcEnd-sr​​cBegin) - 1 自动计算。这是真的吗?
  • 他计算的时候为什么重要?也许它不在乎,只是简单地尝试写
【解决方案2】:

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

palindrome.getChars(0, len, tempCharArray, 0);  

【讨论】:

    【解决方案3】:

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

    char[] tempCharArray = new char[len + 1]; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2013-03-01
      • 2011-09-19
      相关资源
      最近更新 更多