當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java AbstractList get()用法及代碼示例


java.util.AbstractList 類的 get() 方法用於返回此列表中指定位置的元素。

用法:

public abstract E get(int index)

參數:該方法將元素的索引作為參數,即要返回的元素。

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

異常:如果索引超出範圍(索引 = 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<Integer>
            AbstractList<Integer>
                arrlist1 = new ArrayList<Integer>();
  
            // 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<Integer>
            AbstractList<Integer>
                arrlist1 = new ArrayList<Integer>();
  
            // 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




相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 AbstractList get() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。