ArrayList.indexOf()
Java ArrayList()
ArrayList.indexOf(element) Position ( Number ) of element present inside the ArrayList.
element : required, the element name.
It returns the position ( number ) of the first occurrence of the input element. -1 is returned if no matching element is found.
Examples with output
« add()
ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");
System.out.println(languages.indexOf("PHP")); // 1
System.out.println(languages.indexOf("Python")); //2
System.out.println(languages.indexOf("HTML")); // -1
Output ( HTML is not present inside our ArrayList. )
1
2
-1
If multiple elements are present then first matching position is returned.
ArrayList<Integer> marks = new ArrayList<Integer>(3);
marks.add(55);
marks.add(54);
marks.add(55);
marks.add(54);
System.out.println(marks.indexOf(54)); //1
To get the last matching position of the element we can use lastIndexOf() .
« ArrayList Tutorials
« Java
This article is written by plus2net.com team.
Be the first to post comment:
plus2net.com