📌  相关文章
📜  Java中的 AbstractList get() 方法及示例

📅  最后修改于: 2022-05-13 01:55:42.502000             🧑  作者: Mango

Java中的 AbstractList get() 方法及示例

Java.util.AbstractList类的get()方法用于返回该列表中指定位置的元素。

句法:

public abstract E get(int index)

参数:该方法将元素的索引作为参数,即要返回的元素。

返回值:此方法返回此列表中指定位置的元素

异常:如果索引超出范围 (index = size()),此方法将引发IndexOutOfBoundsException

下面是说明get()方法的示例。

示例 1:

// Java program to demonstrate
// get() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of AbstractList
            AbstractList
                arrlist1 = new ArrayList();
  
            // Populating arrlist1
            arrlist1.add(10);
            arrlist1.add(20);
            arrlist1.add(30);
            arrlist1.add(40);
            arrlist1.add(50);
  
            // print arrlist1
            System.out.println("ArrayListlist : "
                               + arrlist1);
  
            // getting the value at the index 3
            // using get() method
            int value = arrlist1.get(3);
  
            // print the value
            System.out.println("Element at index 3 : "
                               + value);
        }
  
        catch (IndexOutOfBoundsException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
ArrayListlist : [10, 20, 30, 40, 50]
Element at index 3 : 40

示例 2:

// Java program to demonstrate
// get() method
// for IndexOutOfBoundsException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
        try {
  
            // Creating object of AbstractList
            AbstractList
                arrlist1 = new ArrayList();
  
            // Populating arrlist1
            arrlist1.add(10);
            arrlist1.add(20);
            arrlist1.add(30);
            arrlist1.add(40);
            arrlist1.add(50);
  
            // print arrlist1
            System.out.println("ArrayListlist : "
                               + arrlist1);
  
            // getting the value at the index 7
            // using get() method
            System.out.println("\nTrying to get "
                               + "the element from out"
                               + " of range index ");
            int value = arrlist1.get(7);
  
            // print the value
            System.out.println("Element at index 7 : "
                               + value);
        }
  
        catch (IndexOutOfBoundsException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
ArrayListlist : [10, 20, 30, 40, 50]

Trying to get the element from out of range index 
Exception thrown : java.lang.IndexOutOfBoundsException: Index: 7, Size: 5