[java] Java ArrayList Index

int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

This question is related to java arraylist

The answer is


Here is how I would write it.

String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);

Read more about Array and ArrayList

List<String> aList = new ArrayList<String>();
aList.add("apple");   
aList.add("banana");   
aList.add("orange");   
String result = alist.get(1);  //this will retrieve banana

Note: Index starts from 0 i.e. Zero


The big difference between primitive arrays & object-based collections (e.g., ArrayList) is that the latter can grow (or shrink) dynamically. Primitive arrays are fixed in size: Once you create them, their size doesn't change (though the contents can).


In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:

ArrayList<String> alist = new ArrayList<String>();
alist.add("apple"); 
alist.add("banana"); 
alist.add("orange"); 

System.out.println( alist.get(1) );

Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.


Using an Array:

String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element

Using a List

ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));