首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ArrayList indexOf

ArrayList indexOf
EN

Stack Overflow用户
提问于 2014-05-27 12:46:26
回答 3查看 763关注 0票数 2

我刚刚开始学习Java语言中的ArrayList类。我用下面的代码测试了ArrayList类及其方法:

代码语言:javascript
复制
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,因此索引中应该有两个对象。whereIsitwhereIsit2的输出都是0。不应该是0 1吗??

EN

回答 3

Stack Overflow用户

发布于 2014-05-27 12:48:43

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

所以你的列表看起来像这样

代码语言:javascript
复制
["", ""]

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

附注:

请记住,Java是通过值传递的。变量无关紧要。重要的是被传递的引用的值。

票数 10
EN

Stack Overflow用户

发布于 2014-05-27 13:08:05

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

代码语言:javascript
复制
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.  

代码语言:javascript
复制
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.
票数 0
EN

Stack Overflow用户

发布于 2014-05-27 13:08:46

在这里,您只创建了两个对象,并且没有值,因此它将被视为空字符串。因此,Indexof将返回给定对象的第一个匹配项。

如果你给s和b分配了不同的值,那么就会得到你所期望的结果。请尝试使用以下代码。

代码语言:javascript
复制
    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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23881232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档