查找ArrayList元素的下标

package com.javacodegeeks.snippets.core;

import java.util.ArrayList;

public class SearchElementsInArrayList {

	public static void main(String[] args) {

		// Create an ArrayList and populate it with elements
		ArrayList arrayList = new ArrayList();
		arrayList.add("element_1");
		arrayList.add("element_2");
		arrayList.add("element_3");
		arrayList.add("element_1");

		/*
		 * 
		 * boolean contains(Object element) operation returns true
		 * 
		 * if the ArrayList contains the specified object, false otherwise.
		 */
		boolean found = arrayList.contains("element_2");
		System.out.println("Found element_2 : " + found);

		/*
		 * 
		 * int indexOf(Object element) operation returns the index of the
		 * 
		 * first occurance of the specified element in ArrayList or -1 if
		 * 
		 * the specific element is not found. To get the index of the last
		 * 
		 * occurance of the specified element in ArrayList use the
		 * 
		 * int lastIndexOf(Object element) operation instead.
		 */
		int index = arrayList.indexOf("element_3");
		System.out.println("Found element_3 : " + (index == -1 ? false : true)
				+ ", in position : " + index);

		int lastIndex = arrayList.lastIndexOf("element_1");
		System.out.println("Found element_1 : "
				+ (lastIndex == -1 ? false : true) + ", in position : "
				+ lastIndex);

	}
}
原文: http://examples.javacodegeeks.com/core-java/util/arraylist/search-elements-in-arraylist-example/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值