通过索引从集合获取值的最佳方式 [英] Best way to get value from Collection by index

查看:322
本文介绍了通过索引从集合获取值的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过索引从java.util.Collection获取值的最好方法是什么?

What is the best way to get value from java.util.Collection by index?

推荐答案

Collection 避免专门讨论索引,因为它可能对特定集合没有意义。例如, List 意味着某种形式的排序,但 Set 不会。

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

    Collection<String> myCollection = new HashSet<String>();
    myCollection.add("Hello");
    myCollection.add("World");

    for (String elem : myCollection) {
        System.out.println("elem = " + elem);
    }

    System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

给我:

    elem = World
    elem = Hello
    myCollection.toArray()[0] = World

同时:

    myCollection = new ArrayList<String>();
    myCollection.add("Hello");
    myCollection.add("World");

    for (String elem : myCollection) {
        System.out.println("elem = " + elem);
    }

    System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

给我:

    elem = Hello
    elem = World
    myCollection.toArray()[0] = Hello

为什么要这样做?你不能只是迭代集合吗?

Why do you want to do this? Could you not just iterate over the collection?

这篇关于通过索引从集合获取值的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆