英文:
generic list add method
问题
我尝试创建一个方法,在此列表的指定位置插入元素。然后通过将该位置处的元素和随后的元素右移一个位置,使它们的索引加一。我知道有一个这个方法的快捷方式,但我应该自己完成它,这是我尝试做的,但它没有生效。
private T a[];
private int count;
private int size = 0;
public int size() { return size; }
public void add(int index, T t) throws Exception {
if (index < 0 || index >= a.length) {
throw new IndexOutOfBoundsException();
}
Object[] temp = new Object[a.length + 1];
for (int k = 0, j = 0; j < temp.length; ++k, ++j) {
if (k == index) {
temp[index] = t;
--k;
} else {
temp[j] = a[index]; //
}
}
a = (T[]) temp;
}
英文:
I tried to make method which inserts element at the specified position in this list.
Then Shifts the element & subsequent elements currently at that position to the
Right by adding one to their indices, i know there is shortcut for this method but I am suppose to do it, here what i tried to do but it's not working.
private T a[];
private int count;
private int size = 0;
public int size() { return size; }
public void add(int index,T t) throws Exception {
if (index < 0 || index > = a.length){
throw new IndexOutOfBoundsException();
}
Object[] temp = new Object[a.length + 1];
for (int k = 0, j = 0; j < temp.length; ++ k, ++ j){
if ( k == index ) {
temp[index] = t;
--k;
} else {
temp[j] = a[index]; //
}
}
a = (T[]) temp;
}
答案1
得分: 1
移动元素的诀窍是从右边开始,所以:
for (int i = size; i > index; i--) {
a[i] = a[i - 1];
}
顺便说一下,当增加大小时,通常应该将其大小翻倍,而不仅仅增加1。
英文:
The trick to shifting is to start from the right, so:
for (int i = size; i > index; i--) {
a[i] = a[i - 1];
}
btw, when increasing size, normallyyou would double its size,rather than just growing by 1.
答案2
得分: 0
我更正了你的 'for' 代码块,试试这个:
for (int k = 0, j = 0; j < temp.length; ++k, ++j) {
if (k == index) {
temp[index] = t;
--k;
index = -1;
} else {
temp[j] = a[k];
}
}
我添加了2处修正:
index = -1;
- 为了只在满足条件时进入if语句一次,否则它会不断进入条件内部。temp[j] = a[k];
- 替换为 a[k],你之前总是从 a[index] 取值,也就是同一个位置,这是错误的。
祝你好运
英文:
I corrected your 'for' block, try this:
for (int k = 0, j = 0; j < temp.length; ++k, ++j){
if ( k == index ) {
temp[index] = t;
--k;
index = -1;
} else {
temp[j] = a[k];
}
}
2 fixes i added:
index = -1;
- In order to enter the if condition only 1 time, else it will constantly enter the conditiontemp[j] = a[k];
- replaced to a[k], you was always taking value from a[index] means the same place, this is incorrect.
good luck
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论