Collections

Arraylist Java get() element Code With Examples

Table of Contents

Program

import java.util.ArrayList;
import java.util.LinkedList;
public class ArrayListGetIndexOf {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	ArrayList<String> a1 = new ArrayList<String>();
				a1.add("runnable");
				a1.add("start");
				a1.add("sleep");
				a1.add("setname");
				a1.add("join");
				a1.add("run");
		        	a1.add("start");
		        	a1.add("run");
		        	String s1 ="java class in chrompet";
		        	int index = s1.indexOf("e");
				System.out.println("position of char:" +index);				
				System.out.println(a1.get(2));
				System.out.println(a1.get(0));
				System.out.println(a1.get(5));
		        System.out.println("Index of : "+a1.indexOf("one"));
				System.out.println("Index of : "+a1.indexOf("run"));
				System.out.println("Index of : "+a1.indexOf("sleep"));
				System.out.println("Last index of : "+a1.lastIndexOf("run"));
				System.out.println("Last index of : "+a1.lastIndexOf("setname"));
				System.out.println("Last index of : "+a1.lastIndexOf("start"));
				
			 }
		
	}

Output

   position of char:20
	sleep
	runnable
	run
	Index of : -1
	Index of : 5
	Index of : 2
	Last index of : 7
	Last index of : 3
	Last index of : 6 

Description

public E get​(int index)

     Reads the char at  current position
     Returns the element at the specified position in this list.

Specified by:

get in interface List <E>

Specified by:

get in class AbstractList<E>

Parameters:

index – index of the element to return

Returns:

the element at the specified position in this list

Throws:

IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())

public int indexOf​(Object o)

Returns the index of the first occurrence of the specified element in this list,
or -1 if this list does not contain the element.
More formally, returns the lowest index i such that Objects.equals(o, get(i)),
or -1 if there is no such index.

Specified by:

indexOf in interface List<E>

Overrides:

indexOf in class AbstractList<E>

Parameters:

o – element to search for

public int lastIndexOf​(Object o)

Returns the index of the last occurrence of the specified element in this list,
or -1 if this list does not contain the element. More formally, returns the
highest index i such that Objects.equals(o, get(i)), or -1 if there is no such index.

Specified by:

lastIndexOf in interface List<E>

Overrides:

lastIndexOf in class AbstractList<E>

Parameters:

o – element to search for

Returns:

the index of the last occurrence of the specified element in this list,
or -1 if this list does not contain the element