获取ArrayList某个对象的位置

转载网址:http://www.yiibai.com/java/util/arraylist_indexof.html

java.util.ArrayList.indexOf(Object) 方法返回指定元素的第一个匹配项的索引在此列表中,或者-1,如果此列表中不包含该元素。

声明

以下是java.util.ArrayList.indexOf()方法的声明

public int indexOf(Object o)

参数

  • o -- 要搜索的元素。

返回值

此方法返回指定元素的第一个匹配项的索引在此列表中,或者如果此列表中不包含该元素返回-1。

异常

  • NA

例子

下面的示例演示java.util.ArrayList.indexOf()方法的用法。

package com.yiibai;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<String> arrlist = new ArrayList<String>(5);

    // use add() method to add values in the list
    arrlist.add("G");
    arrlist.add("E");
    arrlist.add("F");
    arrlist.add("M");
	
    System.out.println("Size of list: " + arrlist.size());

    // let us print all the values available in list
    for (String value : arrlist) {
      System.out.println("Value = " + value);
    }  

    // retrieving the index of element "E"
    int retval=arrlist.IndexOf("E");
    System.out.println("The element E is at index " + retval);
  }
}   

让我们来编译和运行上面的程序,这将产生以下结果:

Size of list: 4
Value = G
Value = E
Value = F
Value = M
The element E is at index 1
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值