java 如何从数组中删除一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14805378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete an element from an array?
提问by Mohammed Ahmed
I'm trying to drop a student from course, and this is what i got so far..
我正试图让一名学生离开课程,这就是我到目前为止所得到的..
public void dropStudent() {
String id;
System.out.println(" Enter student ID " );
id = Keyboard.readString();
for ( int i = 0; i <= students.length - 1; i++)
{
if (id.equals(students[i].displayId()))
{
for (int j = i; j <= students.length - 1; j++)
{
students[i] = students[i+1];
}
}
}
}
So the first loop is for each element of the array, the if statement is to check if the id entered match's a student's id from the array. the second "For" is to shift the elements back. when i try it, it does delete a specific student. but instead of shifting the elements back, it just copies the next element in both places. i tried to set the element to null, but it didn't work.
所以第一个循环是针对数组的每个元素,if 语句是检查输入的 id 是否与数组中的学生 id 匹配。第二个“For”是将元素移回。当我尝试时,它确实删除了一个特定的学生。但不是将元素移回,它只是在两个地方复制下一个元素。我试图将元素设置为 null,但没有奏效。
so any suggestions please ? i'm also not allowed to use array list or other things.
所以有什么建议吗?我也不允许使用数组列表或其他东西。
回答by matt.moser
You cannot alter the size of a Java array after instantiation. If all that's needed is returning an array without the student id. You'd want to create a new array with one fewer element, and iterate over the original array, copying all but the id you want to remove.
实例化后不能更改 Java 数组的大小。如果只需要返回一个没有学生 ID 的数组。您想创建一个少一个元素的新数组,并迭代原始数组,复制除要删除的 id 之外的所有内容。
Normally, you'd want to use lists for this. But given your constraints, that's how I'd tackle it.
通常,您需要为此使用列表。但鉴于你的限制,这就是我解决它的方式。
Something like:
就像是:
public String[] dropStudent(String delete, String[] students){
int length=students.length-1, i=0;
String[] remainingStudents= new String[length];
for(String student: students){
// catch the edge case where 'delete' is not found, and avoid the ArrayIndexOutOfBoundsException
if(i==remainingStudents.length){
return students;
}
// Add the any non-matching students to the final array.
if(!student.equals(delete)){
remainingStudents[i]=student;
i++;
}
}
return remainingStudents;
}
回答by Cyrille Ka
Replace:
替换:
students[i] = students[i+1];
with:
和:
students[j] = students[j+1];
Indeed, you want to go through all the rest of the array with your loop variable j
and not with i
which represents the index of the student to be deleted.
实际上,您希望使用循环变量遍历数组的所有其余部分,j
而不是使用i
which 表示要删除的学生的索引。
Also, you need to replace your loop:
此外,您需要替换循环:
for (int j = i; j <= students.length - 1; j++)
with
和
for (int j = i; j <= students.length - 2; j++)
(notice the 1 changed in a 2)
(注意 1 变成了 2)
The reason for this is that you are accessing students
with the index j+1, which, if j == students.length - 1, will be equal to students.length, and therefore you will have an ArrayOutOfBounException.
这样做的原因是您正在使用students
索引 j+1进行访问,如果 j == student.length - 1,它将等于 student.length,因此您将有一个 ArrayOutOfBounException。
At last, you have to set the last element of the array as null(or the last student will be duplicated). Or better yet, you can resize the array (that is create a new array and copy the new list of students in it).
最后,您必须将数组的最后一个元素设置为空(否则最后一个学生将被复制)。或者更好的是,您可以调整数组的大小(即创建一个新数组并复制其中的新学生列表)。
Also, if you have several copies of the students in the array and you just want to remove the first, you have to add break
when you have found the element to be removed.
此外,如果数组中有多个学生副本,而您只想删除第一个,则必须在break
找到要删除的元素后添加。
回答by dreamcrash
You can do the following:
您可以执行以下操作:
You want to eliminate a given 'x' position of the array, you just make a sift left of all the elements on the next position of the array. Keep a size variable an decrease it;
You can have a flag on class that have the student information, and when you deleted you mark this flag as deleted. False -> deleted, True -> not deleted.
You can use an ArrayList instead of an array.
您想消除数组的给定“x”位置,只需在数组的下一个位置的所有元素的左侧进行筛选。保持大小变量并减少它;
您可以在包含学生信息的班级上设置一个标志,并在删除时将此标志标记为已删除。假 -> 已删除,真 -> 未删除。
您可以使用 ArrayList 而不是数组。
If the order do not matter you can simply do:
如果顺序无关紧要,您可以简单地执行以下操作:
for ( int i = 0; i <= students.length - 1; i++)
{
if (id.equals(students[i].displayId()))
{
students[i] = students[students.length-1];
}
}
Just take the last element and fit the actual gap. However, you have to do something with the last position, someway of mark it as empty (you can set to null for example).
只需取最后一个元素并适应实际差距。但是,您必须对最后一个位置做一些事情,以某种方式将其标记为空(例如,您可以设置为 null)。
If the order do matter, then you can do also by using an auxiliary array:
如果顺序很重要,那么您也可以使用辅助数组来完成:
Students [] removeFrom(Students [] old_array, int pos)
{
Students [] new_array = new Students[old_array-1];
for (int j = 0; j < i ; j++) new_array[j] = old_array[j];
for (int j = i; j < new_array.length; j++) new_array[j] = old_array[j+1];
return new_array;
}
in :
在 :
for ( int i = 0; i <= students.length - 1; i++)
{
if (id.equals(students[i].displayId()))
{
students = removeFrom(students, i);
}
}
回答by Oneb
- use the variable "j" in your second loop
- fix your logic so that "j+1" will not result to array index out of bounds
- 在第二个循环中使用变量“j”
- 修复您的逻辑,以便“j+1”不会导致数组索引越界