Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList Index

Tags:

java

arraylist

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

like image 606
Woong-Sup Jung Avatar asked Nov 30 '10 11:11

Woong-Sup Jung


People also ask

What is an index in Java ArrayList?

The Java ArrayList indexOf() method returns the position of the specified element in the arraylist. The syntax of the indexOf() method is: arraylist.indexOf(Object obj) Here, arraylist is an object of the ArrayList class.

Does ArrayList have index?

indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

How do you add an index to an ArrayList in Java?

add() method is used to add an element at particular index in Java ArrayList.

Are Arraylists 0 indexed?

The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value.


1 Answers

You have ArrayList all wrong,

  • You can't have an integer array and assign a string value.
  • You cannot do a add() method in an array

Rather do this:

List<String> alist = new ArrayList<String>(); alist.add("apple"); alist.add("banana"); alist.add("orange");  String value = alist.get(1); //returns the 2nd item from list, in this case "banana" 

Indexing is counted from 0 to N-1 where N is size() of list.

like image 118
Buhake Sindi Avatar answered Sep 20 '22 03:09

Buhake Sindi