當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java CopyOnWriteArrayList lastIndexOf(E e, int index)用法及代碼示例

Java CopyOnWriteArrayList 類的 lastIndexOf(E e, int index) 方法返回此列表中指定元素最後一次出現的索引,該索引從索引向後搜索。如果未找到該元素,則此方法將返回 -1。

用法:

public int lastIndexOf(E e, int index)

參數:

e- 要搜索的元素

index- 開始向後搜索的索引

返回值:

此方法返回元素在此列表中小於或等於 index 的位置最後一次出現的索引。如果未找到該元素,則此方法返回 -1。

例子1

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListLastIndexOfExample1{
	
	public static void main(String[] args) {
		//Initializing CopyOnWriteArrayList of Integers
		CopyOnWriteArrayList<Integer>numbers = new CopyOnWriteArrayList<>(new Integer[] {1,2,1,4,5,3,3,8});
		//Prints the index of the last occurrence of the specified element in this list, searching backwards from index, or returns -1 if the element is not found.
		System.out.println("Last Index of 3 is:" + numbers.lastIndexOf(3, 7));	
			}
	}

輸出:

Last Index of 3 is:6

例子2

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListLastIndexOfExample2{
	
	public static void main(String[] args) {
		//Initializing CopyOnWriteArrayList of Integers
		CopyOnWriteArrayList<Integer>numbers = new CopyOnWriteArrayList<>(new Integer[] {1,2,1,4,5,3,3,8});
		//Prints the index of the last occurrence of the specified element in this list, searching backwards from index, or returns -1 if the element is not found.
		System.out.println("Last Index of 3 is:" + numbers.lastIndexOf(11, 7));
			}
		}

輸出:

Last Index of 11 is:-1

例子3

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListLastIndexOfExample3{
	
	public static void main(String[] args) {
		//Initializing CopyOnWriteArrayList of Strings
		CopyOnWriteArrayList<String>listOfNames = new CopyOnWriteArrayList<>(new String[] {"Tom","Harry","John","John","John","Jerry"});
		//Prints the index of the last occurrence of the specified element in this list, searching backwards from index, or returns -1 if the element is not found.
		System.out.println("Last Index of John is:" + listOfNames.lastIndexOf("John", 5));
			}
		}

輸出:

Last Index of John is:4

示例 4

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListLastIndexOfExample4{
	
	public static void main(String[] args) {
		//Initializing CopyOnWriteArrayList of Strings
		CopyOnWriteArrayList<String>listOfNames = new CopyOnWriteArrayList<>(new String[] {"Tom","Harry","John","John","John","Jerry"});
		//Prints the index of the last occurrence of the specified element in this list, searching backwards from index, or returns -1 if the element is not found.
		System.out.println("Last Index of Lincoln is:" + listOfNames.lastIndexOf("Lincoln", 5));	
			}	
	}

輸出:

Last Index of Lincoln is:-1






相關用法


注:本文由純淨天空篩選整理自 Java CopyOnWriteArrayList lastIndexOf(E e, int index) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。