How to use getray () method of ArrayList

I am new to java (& for OOP too) and I am trying to understand about the ArrayList class but I don't understand how to use get (). I tried searching the net but did not find anything useful.

+7
source share
4 answers

Here is the official documentation of ArrayList.get () .

In any case, it is very simple, for example

ArrayList list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); String str = (String) list.get(0); // here you get "1" in str 
+19
source

You use List#get(int index) to get an object with index in the list. You use it like this:

 List<ExampleClass> list = new ArrayList<ExampleClass>(); list.add(new ExampleClass()); list.add(new ExampleClass()); list.add(new ExampleClass()); ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2); 
+3
source

Would that help?

 final List<String> l = new ArrayList<String>(); for (int i = 0; i < 10; i++) l.add("Number " + i); for (int i = 0; i < 10; i++) System.out.println(l.get(i)); 
+1
source

Positively and simply, get(int index) returns the element at the specified index.

So we have an ArrayList of String :

 List<String> names = new ArrayList<String>(); names.add("Arthur Dent"); names.add("Marvin"); names.add("Trillian"); names.add("Ford Prefect"); 

What can be visualized as: A visual representation of the list of arrays Where 0, 1, 2, and 3 denote the ArrayList indices.

Let's say we wanted to get one of the names that we would make: String name = names.get(1); Which returns the name in index 1.

Getting an item at index 1 Therefore, if we printed the name System.out.println(name); The output would be Marvin .

+1
source

All Articles