从Java向量中的指定索引中删除元素
可以使用remove()方法删除Java向量中指定索引处的元素。此方法存在于Java.util.Vector 类中。我们可以传递将被删除的元素的索引作为参数。 remove() 方法 return 方法返回被删除的元素。
句法 :
public removed_element remove(int index)
参数:要删除的元素的索引。
返回类型:此方法返回从列表中删除的元素。
异常:如果索引超出范围,此方法将抛出IndexOutOfBoundsException 。
代码:
Java
// Java program for removing element
// at specified index
import java.util.Vector;
public class GFG {
public static void main(String arg[])
{
// Create an Vector
Vector vector = new Vector<>();
// Add elements in the vector
vector.add(10);
vector.add(20);
vector.add(30);
vector.add(20);
vector.add(40);
// display original vector
System.out.println("Values in vector: " + vector);
// remove 2 index element and store the value in r
int r = vector.remove((2));
// display removed element
System.out.println("Removed element: " + r);
// display vector after 2 index element
System.out.println("Values in vector: " + vector);
}
}
Java
// Java program to show the exception
// of remove() method
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList arrlist = new ArrayList(5);
// use add() method to add elements in the deque
arrlist.add(26);
arrlist.add(18);
arrlist.add(31);
arrlist.add(42);
System.out.println("Size of list: " + arrlist.size());
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
// Removes element at 5th position
// which is not present in the list
// and will therefore give IndexOutOfBound exception
arrlist.remove(4);
System.out.println("Now, Size of list: " + arrlist.size());
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
输出
Values in vector: [10, 20, 30, 20, 40]
Removed element: 30
Values in vector: [10, 20, 20, 40]
remove() 方法中的异常:
当我们尝试删除大于或等于数组列表大小的索引处的元素时,编辑器会在运行时给我们一个IndexOutOfBound 异常。
Java
// Java program to show the exception
// of remove() method
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList arrlist = new ArrayList(5);
// use add() method to add elements in the deque
arrlist.add(26);
arrlist.add(18);
arrlist.add(31);
arrlist.add(42);
System.out.println("Size of list: " + arrlist.size());
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
// Removes element at 5th position
// which is not present in the list
// and will therefore give IndexOutOfBound exception
arrlist.remove(4);
System.out.println("Now, Size of list: " + arrlist.size());
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 4