【问题标题】:ArrayList indexOfArrayList indexOf
【发布时间】:2014-05-27 04:46:25
【问题描述】:

我刚开始学习 Java 中的 ArrayList 类。我有以下代码测试 ArrayList 类及其方法:

import java.util.ArrayList;

public class NewArrayList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<String> myList = new ArrayList<String>();

        String s = new String();
        myList.add(s);
        String b = new String();
        myList.add(b);

        int theSize = myList.size();
        System.out.println("ArrayList size: " + theSize);

        boolean isTrue = myList.contains(s);
        System.out.println(isTrue);

        int whereIsIt = myList.indexOf(s);
        System.out.println(whereIsIt);
        int whereIsIt2 = myList.indexOf(b);
        System.out.println(whereIsIt2);

    }

}

indexOf 方法显示对象的索引。因此,由于我在 myList ArrayList 对象引用中添加了两个对象 sb,因此它的索引内应该有 2 个对象。 whereIsitwhereIsit2 的输出都是 0。不应该是0 1吗??

【问题讨论】:

    标签: java arraylist indexof


    【解决方案1】:

    您正在向列表中添加两个具有相同值(空字符串)的 String 对象。

    所以你的列表看起来像

    ["", ""]
    

    然后您将调用indexOf("") 的等效项,其中indexOf(..) 使用Object#equals(Object) 方法来比较对象。列表中的第一个元素等于"",因此返回索引。

    【讨论】:

      【解决方案2】:

      这里你只创建了两个对象,它们没有任何值,所以它将被视为空字符串。所以 Indexof 将返回给定对象的第一次出现。

      如果您为 s 和 b 分配不同的值,则会得到您所期望的结果。请尝试以下代码。

          String s = "String1";
          myList.add(s);
          String b = "String2";
          myList.add(b);
      
          int whereIsIt = myList.indexOf(s);
          System.out.println(whereIsIt);
          int whereIsIt2 = myList.indexOf(b);
          System.out.println(whereIsIt2);
      

      【讨论】:

        【解决方案3】:

        使用http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html前请阅读文档中的方法描述

        int     indexOf(Object o)
        Returns the index of the first occurrence of the specified element in this list, or -1   if    this list does not contain the element.  
        

        public int lastIndexOf(Object o)
        
        Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
        

        【讨论】:

          猜你喜欢
          • 2012-08-26
          • 1970-01-01
          • 2017-04-03
          • 2013-10-26
          • 1970-01-01
          • 1970-01-01
          • 2018-09-18
          • 2011-03-08
          • 2011-02-15
          相关资源
          最近更新 更多