Java Vector get() 方法



描述

Java Vector get(int index) 方法用於返回此 Vector 中指定index 位置處的元素。

宣告

以下是java.util.Vector.get() 方法的宣告

public E get(int index)

引數

index − 這是要返回的元素的索引位置。

返回值

方法呼叫返回指定索引處的物件。

異常

ArrayIndexOutOfBoundsException − 如果訪問的索引/位置超出範圍,則丟擲此異常。

按索引獲取整數 Vector 元素的示例

以下示例演示了 Java Vector get(index) 方法對整數的使用。我們使用 add() 方法為每個元素向 Vector 物件新增幾個整數,並使用 get(index) 方法按索引獲取其中一個元素並列印它。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {
      
      // create an empty array list 
      Vector<Integer> vector = new Vector<>();

      // use add() method to add elements in the vector
      vector.add(20);
      vector.add(30);
      vector.add(20);
      vector.add(30);
      vector.add(15);
      vector.add(22);
      vector.add(11);

      // let us print the 3rd element
      System.out.println("3rd Element = " + vector.get(2));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

3rd Element = 20

按索引獲取字串 Vector 元素的示例

以下示例演示了 Java Vector get(index) 方法對字串的使用。我們使用 add() 方法為每個元素向 Vector 物件新增幾個字串,並使用 get(index) 方法按索引獲取其中一個元素並列印它。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {
      
      // create an empty array list
      Vector<String> vector = new Vector<>();

      // use add() method to add elements in the vector
      vector.add("Welcome");
      vector.add("To");
      vector.add("Tutorialspoint");
	  
      // let us print the 3rd element
      System.out.println("3rd Element = " + vector.get(2));     
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

3rd Element = Tutorialspoint

按索引獲取物件 Vector 元素的示例

以下示例演示了 Java Vector get(index) 方法對 Student 物件的使用。我們使用 add() 方法為每個元素向 Vector 物件新增幾個 Student 物件,並使用 get(index) 方法按索引獲取其中一個元素並列印它。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {

      // create an empty vector
      Vector<Student> vector = new Vector<>();

      // use add() method to add elements in the vector
      vector.add(new Student(1, "Julie"));
      vector.add(new Student(2, "Robert"));
      vector.add(new Student(3, "Adam"));

      // let us print the 3rd element
      System.out.println("3rd Element = " + vector.get(2));      
   }
}

class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

3rd Element = [ 3, Adam ]
java_util_vector.htm
廣告