![](/img/trans.png)
[英]split a string in java into equal length substrings while maintaining word boundaries
[英]Array boundaries on java and .length
keys數組定義如下:
keys = new char[] {resolv, 'А', 'Б', 'В', 'Г', 'Д', 'Е',
'Ё', 'Ж', 'З', 'И', 'Й', 'К',
'Л', 'М', 'Н', 'О', 'П', 'Р',
'С', 'Т', 'У', 'Ф', 'Х', 'Ц',
'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь',
'Э', 'Ю', 'Я'};
'resolv'是一個常量char值0x00,但這與此問題無關。
現在,這段代碼有時會引發“java.lang.ArrayIndexOutOfBoundsException:length = 34; index = 34”異常:
protected void LoadKeyRects() {
keyRects = new Rect[keys.length];
// Solve key
keyRects[0] = resRect;
// Rest of keys
int x, y;
for (int i=1; i<keys.length; i++) {
y = 214 + ( 87 * ((i-1)/11));
x = 7 + (((i-1)%11)*71);
keyRects[i] = new Rect (x, y, x+71, y+87);
}
}
到目前為止,我還沒有能夠自己重現錯誤,但我從第三方設備的BugSense獲得了足夠的報告來關注它。 似乎有時keyRects [i]可能會引用keyRects [keys.length]盡管i
有任何想法嗎?
我可以在for
循環中看到問題。 如果您沒有訪問字段本身,則使用超出范圍的字段來結束迭代,這是完全錯誤的。 如果你這樣做,你應該采用不同的方式。 兩個例子:
protected void LoadKeyRects() {
keyRects = new Rect[keys.length];
// Solve key
keyRects[0] = resRect;
// Rest of keys
int x, y;
for (int i=1; i<keyRects.length; i++) {
y = 214 + ( 87 * ((i-1)/11));
x = 7 + (((i-1)%11)*71);
keyRects[i] = new Rect (x, y, x+71, y+87);
}
}
這將正常工作,沒有任何ArrayIndexOutOfBoundsException
肯定。 如果您需要訪問甚至修改keys
數組,請執行以下操作:
protected void LoadKeyRects() {
final char[] localKeys = keys;
keyRects = new Rect[localKeys.length];
// Solve key
keyRects[0] = resRect;
// Rest of keys
int x, y;
for (int i=1; i<localKeys.length; i++) {
y = 214 + ( 87 * ((i-1)/11));
x = 7 + (((i-1)%11)*71);
keyRects[i] = new Rect (x, y, x+71, y+87);
}
// if you need to change the keys, uncomment the next line
// keys = localKeys;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.