Java教程

Java Vector firstElement()

Java Vector类的 firstElement()方法用于获取第一个元素(在索引0处)

语法:

以下是 firstElement()方法的声明:
public E firstElement()

参数:

此方法不接受任何参数。

返回:

firstElement()方法返回正在使用的向量的第一个分量。

异常:

NoSuchElementException -如果向量的元素为空,则此方法引发异常。

兼容性版本:

Java 1.2及更高版本

示例1:

import java.util.*;
public class VectorFirstElementExample1 {  
    public static void main(String arg[]) {   
        //Create an empty vector
        Vector<Integer> vec = new Vector<>();
        //Add element in the vector
        vec.add(91);
        vec.add(21);
        vec.add(31);      
        vec.add(41);
        vec.add(51);
        //Get the first element
        System.out.println("First element of the vector is = "+vec.firstElement());    
        }            
}
输出:
First element of the vector is = 91

示例2:

import java.util.*;
public class VectorFirstElementExample2 {  
    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");
          colors.add("Pink");
          //Get the element at specified index
          System.out.println("First color of this vector = " +colors.firstElement());       
        }            
}
输出:
First color of this vector = White

示例3:

import java.util.*;
public class VectorFirstElementExample3 {  
    public static void main(String arg[]) {   
        //Create an empty vector
        Vector<Integer> vecObject = new Vector<Integer>();             
        //Get the element at specified index
        System.out.println("First element of the vector = "+vecObject.firstElement());    
        }            
}
输出:
Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Vector.firstElement(Vector.java:511)
    at myPackage.VectorFirstElementExample3.main(VectorFirstElementExample3.java:8)

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