Java Vector elementAt()

Java Vector [Java Vector] Java Vector


elementAt() Java Vector (Vector)

public synchronized E elementAt(int index)

  • index - 0

  • index < 0 || index >= size() ArrayIndexOutOfBoundsException

elementAt()

  1. Vector
  2. Vector Java

elementAt()

import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        // Vector
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
       
        // elementAt()
        String secondFruit = fruits.elementAt(1);
        System.out.println(": " + secondFruit);
       
        // Vector
        for (int i = 0; i < fruits.size(); i++) {
            System.out.println(" " + i + " : " + fruits.elementAt(i));
        }
    }
}

: Banana
 0 : Apple
 1 : Banana
 2 : Cherry

get()

Vector get() elementAt()

//
String fruit1 = fruits.elementAt(1);
String fruit2 = fruits.get(1);

  1. elementAt() Vector get() List
  2. Java get()

elementAt() ArrayIndexOutOfBoundsException

try {
    String fruit = fruits.elementAt(5);  // Vector 3
    System.out.println(fruit);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("");
}

int index = 5;
if (index >= 0 && index < fruits.size()) {
    String fruit = fruits.elementAt(index);
    System.out.println(fruit);
} else {
    System.out.println(" " + index + " ");
}

  1. elementAt() O(1)
  2. Vector elementAt()
  3. ArrayList get()

elementAt() Vector get() Java ArrayList get() Vector

Java Vector [Java Vector] Java Vector