java+vector+remove_Java Vector removeRange()用法及代码示例

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 {

// 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 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 {

// 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()具有受保护的访问。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值