Java教程

Java Vector setSize()

Java Vector类的 setSize()方法用于设置Vector 的大小。如果新大小大于当前大小,则将空项目添加到向量的末尾。否则,将丢弃索引为newSize或更高的所有组件。

语法

以下是 setSize()方法的声明:
Public void setSize(int newSize)

参数

参数 说明 必需/可选
newSize 它是向量的新大小。 必需

返回

setSize()方法不返回任何内容。

异常

ArrayIndexOutOfBoundsException -如果新大小为,则此方法将引发异常。向量为负,即newSize <0。

兼容版本

Java 1.2及更高版本

示例1

import java.util.*;
public class VectorSetSizeExample1 {  
  public static void main(String arg[]) { 
      //Create an empty vector 
      Vector<Integer> vec = new Vector<>();
      //Add elements in the vector
      vec.add(1);
      vec.add(2);
      vec.add(3);
      System.out.println("Components of the vector: "+vec);      
          //Set the new size of the vector
          vec.setSize(6);
          //Displaying the vector elements after setting new size
          System.out.println("Components of the vector after setting new size: ");          
          for (Integer num : vec) {         
             System.out.println("Number = " +num);
      }            
      }
}
输出:
Components of the vector: [1, 2, 3]
Components of the vector after setting new size: 
Number = 1
Number = 2
Number = 3
Number = null
Number = null
Number = null

示例2

import java.util.*;
public class VectorSetSizeExample2 {  
  public static void main(String arg[]) { 
      //Create an empty vector
      Vector < String > colors = new Vector < String > ();
      //Add elements in the vector
          colors.add("White");
          colors.add("Green");
          colors.add("Black");
          //Displaying the vector elements
          System.out.println("Components of a vector: "+colors);
          //Set the new size for the vector
          colors.setSize(6);
          //Displaying the vector elements after setting new size
          System.out.print("Components of a vector after setting new size: "+colors);    
      }            
}
输出:
Components of a vector: [White, Green, Black]
Components of a vector after setting new size: [White, Green, Black, null, null, null]

示例3

import java.util.*;
public class VectorSetSizeExample3 {  
  public static void main(String arg[]) { 
      //Create an empty vector 
      Vector<Integer> vec = new Vector<>();
      //Add elements in the vector
      vec.add(10);
      vec.add(20);
      vec.add(30);      
      //Set the new size of the vector
      vec.setSize(-15);
      //Displaying the vector element
      System.out.println("Vector element after setSize(): " +vec);
      }            
}
输出:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -15
  at java.base/java.util.Vector.setSize(Vector.java:314)
  at myPackage.VectorSetSizeExample3.main(VectorSetSizeExample3.java:12)

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4