Java中的ArrayList get(index)方法及其示例

这个 得到() 方法 ArrayList 在Java中,用于获取列表中指定索引的元素。

null

语法:

get(index)

参数: 要返回的元素的索引。它的数据类型是int。

返回类型: 给定列表中指定索引处的元素。

例外情况: 它抛出 IndexOutOfBoundsException 如果索引超出范围(index=size())

注: 时间复杂性 : ArrayList是构建顶级阵列的列表实现之一。因此,get(index)始终是一个常数时间O(1)操作。

例子:

JAVA

// Java Program to Demonstrate the working of
// get() method in ArrayList
// Importing ArrayList class
import java.util.ArrayList;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an Empty Integer ArrayList
ArrayList<Integer> arr = new ArrayList<Integer>( 4 );
// Using add() to initialize values
// [10, 20, 30, 40]
arr.add( 10 );
arr.add( 20 );
arr.add( 30 );
arr.add( 40 );
// Printing elements of list
System.out.println( "List: " + arr);
// Getting element at index 2
int element = arr.get( 2 );
// Displaying element at specified index
// on console inside list
System.out.println( "the element at index 2 is "
+ element);
}
}


输出

List: [10, 20, 30, 40]the element at index 2 is 30

例2 :演示错误的程序

JAVA

// Java Program to Demonstrate Error Generated
// while using get() method in ArrayList
// Importing ArrayList class
import java.util.ArrayList;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an Empty Integer ArrayList
ArrayList<Integer> arr = new ArrayList<Integer>( 4 );
// Using add() method to insert elements
// and adding custom values
arr.add( 10 );
arr.add( 20 );
arr.add( 30 );
arr.add( 40 );
// Getting element at index 2
int element = arr.get( 5 );
// Print all the elements of ArrayList
System.out.println( "the element at index 2 is "
+ element);
}
}


输出:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4    at java.util.ArrayList.rangeCheck(ArrayList.java:657)    at java.util.ArrayList.get(ArrayList.java:433)    at GFG.main(GFG.java:22)
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享