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
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.
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.
add() method is used to add an element at particular index in Java ArrayList.
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.
You have ArrayList
all wrong,
add()
method in an arrayRather 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With