Best way to get value from Collection by index

前端 未结 10 1517
旧时难觅i
旧时难觅i 2020-12-05 17:08

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

10条回答
  •  抹茶落季
    2020-12-05 17:36

    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 myCollection = new HashSet();
    myCollection.add("Hello");
    myCollection.add("World");
    
    for (String elem : myCollection) {
        System.out.println("elem = " + elem);
    }
    
    System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
    

    gives me:

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

    whilst:

    myCollection = new ArrayList();
    myCollection.add("Hello");
    myCollection.add("World");
    
    for (String elem : myCollection) {
        System.out.println("elem = " + elem);
    }
    
    System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
    

    gives me:

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

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

提交回复
热议问题