数组下标越界 java 问题 急
小弟新手我要写一个类关于array的但是出现数组下标越界packageassignment10;//importjava.util.Arrays;publicclassS...
小弟新手
我要写一个类 关于array 的 但是出现数组下标越界
package assignment10;
//import java.util.Arrays;
public class StringArrayList {
private int capacity;
private String[] words;
private int elementCount;
/* This default constructor creates the array
*
*/
// problem how to hold 10 capacities
// how to null
public StringArrayList () {
words = new String[10];
elementCount = 0;
}
public void append (String s) {
if (elementCount == capacity)
{
// Grow the array.
String[] bigger = new String[capacity*2];
for (int i = 0; i < elementCount; i++)
{
bigger[i] = words[i];
}
capacity = bigger.length;
words = bigger;
}
// Add the element to the next available position
words[elementCount] = s;
elementCount++;
}
public void remove (int pos){
int count = words.length -1;
String [] temp = new String [count];
for(int i =0; i<= count; i++){
if (i<pos)
temp[i] = words[i];
else
temp[i] = words[i+1];
}
words =temp;
}
第一个 append 是添加 如果空间不足扩张2倍
第二个是删除 指定元素 然后它后面的元素会往前移 不如 1 2 3 4 5 我删了3 就变成 1 2 4 5 而不是 1 2 null 4 5. 谢谢各位大神 展开
我要写一个类 关于array 的 但是出现数组下标越界
package assignment10;
//import java.util.Arrays;
public class StringArrayList {
private int capacity;
private String[] words;
private int elementCount;
/* This default constructor creates the array
*
*/
// problem how to hold 10 capacities
// how to null
public StringArrayList () {
words = new String[10];
elementCount = 0;
}
public void append (String s) {
if (elementCount == capacity)
{
// Grow the array.
String[] bigger = new String[capacity*2];
for (int i = 0; i < elementCount; i++)
{
bigger[i] = words[i];
}
capacity = bigger.length;
words = bigger;
}
// Add the element to the next available position
words[elementCount] = s;
elementCount++;
}
public void remove (int pos){
int count = words.length -1;
String [] temp = new String [count];
for(int i =0; i<= count; i++){
if (i<pos)
temp[i] = words[i];
else
temp[i] = words[i+1];
}
words =temp;
}
第一个 append 是添加 如果空间不足扩张2倍
第二个是删除 指定元素 然后它后面的元素会往前移 不如 1 2 3 4 5 我删了3 就变成 1 2 4 5 而不是 1 2 null 4 5. 谢谢各位大神 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询