如何从 Java 列表中获取元素?

javaobject oriented programmingprogramming更新于 2024/12/31 5:32:17

可以使用 get() 方法从列表中检索元素。

语法

E get(int index)

返回此列表中指定位置的元素。

参数

  • index − 要返回的元素的索引。

返回

此列表中指定位置的元素。

抛出

  • IndexOutOfBoundsException −如果索引超出范围(index < 0 || index >= size())。

此处 index 表示列表中元素 E 的索引。如果 index 超出范围,则会抛出 IndexOutOfBoundsException。

示例

以下是使用 get() 方法从列表中获取元素的示例−

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("A");
      list.add("B");
      list.add("C");
      System.out.println("List: " + list);
      System.out.println("List(1): " + list.get(1));
      try {
         System.out.println("List(3): " + list.get(3));
      }catch(IndexOutOfBoundsException e) {
         System.out.println(e);
      }
   }
}

输出

这将产生以下结果 −

List: [A, B, C]
List(1): B
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

相关文章


有用资源