Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use index like array index to access List<T>?

Tags:

java

I am wondering if we can use index to access List

For example:

List<Integer> list;   list[5]     //blah.... 
like image 965
user496949 Avatar asked Mar 26 '11 09:03

user496949


People also ask

Can ArrayList be accessed by index?

Java For TestersThe index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

Can we access list using index in Java?

You can get the elements from a Java List using the index of the elements. You can do so using either the get(int index) method. Here is an example of accessing the elements of a Java List using the element indexes: List<String> listA = new ArrayList<>(); listA.

How do you access a list inside an array?

get(0)[0]; get(0) gives you the first inserted array and [0] gives you the first positiend element in that array. If you are looking for position of A in array, access the array from list with l. get(0) and iterate over the array you got to get the position of A .

How do you access elements of an ArrayList using an index?

To get an element from ArrayList in Java, call get() method on this ArrayList. get() method takes index as an argument and returns the element present in the ArrayList at the index. E element = arraylist_1. get(index);


1 Answers

Since [] is an operator and java does not support operator overloading you can't use it with List. Instead you have to use the set(int index, T value) and get(int index) methods, which may be verbose but provide exact the same functionality.

like image 79
josefx Avatar answered Sep 22 '22 14:09

josefx