Java中Vector的removeRange()方法用于从Vector对象中删除指定范围内的所有元素。它将所有后续元素向左移动。此调用通过(toIndex-fromIndex)元素来缩短Vector,其中toIndex是结束索引,fromIndex是将删除所有元素的开始索引。 (如果toIndex == fromIndex,则此操作无效)
用法:
removeRange(int fromIndex, int toIndex)
参数:有两个参数:
- fromIndex:从中删除索引元素的起始索引。
- toIndex:范围[fromIndex-toIndex)之内,所有元素均被删除。
返回值:此方法不返回任何值。它仅删除指定范围内的所有元素。
异常:如果fromIndex或toIndex超出范围,则此方法将引发IndexOutOfBoundsException(fromIndex = size()或toIndex> size()或toIndex
示例1::
// Java program to understand
// about vector.removeRange() function
mport java.util.*;
// sice vector removeRange() method is protected
// Therefore Vector is inherited
public class GFG extends Vector<String> {
// main method
public static void main(String[] args)
{
// creating GFG object
GFG v = new GFG();
// inserting elements into the vector
v.add("Geeks");
v.add("for");
v.add("Geeks");
v.add("Ankit");
v.add("Mishra");
v.add("MNNIT");
// printing vector before deleting
System.out.println("Vector before calling"
+ " removeRange(): " + v);
// calling removeRange() function
v.removeRange(1, 3);
// printing after removeRange() called
System.out.println("Vector after calling"
+ " removeRange(1, 3): " + v);
}
}
//sice向量removeRange()方法受保护
//因此,Vector是继承的
输出:
//因此,Vector是继承的
输出:
Vector before calling removeRange(): [Geeks, for, Geeks, Ankit, Mishra, MNNIT] Vector after calling removeRange(1, 3): [Geeks, Ankit, Mishra, MNNIT]
示例2::
// Java program to understand
// about vector.removeRange() function
import java.util.*;
// sice vector removeRange() method is protected
// Therefore Vector is inherited
public class GFG extends Vector<String> {
// main method
public static void main(String[] args)
{
// creating GFG object
GFG v = new GFG();
// inserting elements into the vector
v.add("Geeks");
v.add("for");
v.add("Geeks");
v.add("Ankit");
v.add("Mishra");
v.add("MNNIT");
// printing vector before deleting
System.out.println("Vector before calling "
+ "removeRange(): "
+ v);
// calling removeRange() function
try {
// It will generate Runtime Error
v.removeRange(1, 16);
// printing after removeRange() called
System.out.println("Vector after "
+ "calling removeRange(1, 3): "
+ v);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Vector before calling removeRange(): [Geeks, for, Geeks, Ankit, Mishra, MNNIT] java.lang.ArrayIndexOutOfBoundsException
注意:强烈建议,如果我们想在任何类中调用removeRange()方法,则该类必须直接或间接扩展Vector类,否则会得到编译错误:方法removeRange()具有受保护的访问。
相关用法
- Java Stack removeRange()用法及代码示例
- Java Arraylist removeRange()用法及代码示例
- Java Vector contains()用法及代码示例
- Java Vector set()用法及代码示例
- Java Vector add()用法及代码示例
- Java Vector get()用法及代码示例
- Java Vector clear()用法及代码示例
- Java Vector forEach()用法及代码示例
- Java Vector isEmpty()用法及代码示例
- Java Vector removeIf()用法及代码示例
- Java Vector trimToSize()用法及代码示例
- Java Vector containsAll()用法及代码示例
- Java Vector hashCode()用法及代码示例
- Java Vector size()用法及代码示例
- Java Vector equals()用法及代码示例
注:本文由纯净天空筛选整理自ankit15697大神的英文原创作品 Vector removeRange() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。