开发者

In how many ways can we retrieve an object from a collection?

开发者 https://www.devze.com 2023-02-21 00:59 出处:网络
In how many ways can we retr开发者_如何学Goieve an object from a Collection? Two ways which I know are using a for loop and an Iterator. Are there any others?To be strict this depends on which Collec

In how many ways can we retr开发者_如何学Goieve an object from a Collection?

Two ways which I know are using a for loop and an Iterator. Are there any others?


To be strict this depends on which Collection you're talking about. Lists have some ways to retrieve objects in the collection, while Sets have other ways.

For an arbitrary collection (i.e. a collection of which you don't know its concrete type), only the following methods can be used to retrieve the elements:

  • Collection.iterator()
  • Collection.toArray()
  • Collection.toArray(T[] a)

Here is some example code:

Collection<String> col = Arrays.asList("hello", "world");

// Exploiting the fact that collections implement Iterable
for (String s : col)
    System.out.println(s);

// Using iterator explicitly:
Iterator<String> iter = col.iterator();
while (iter.hasNext())
    System.out.println(iter.next());

// Using toArray
System.out.println(Arrays.toString(col.toArray()));

// Using toArray(String[])
System.out.println(Arrays.toString(col.toArray(new String[0])));


Is this homework?

Nevertheless, the ways depend on the collection. A list has a get method, a SortedSet has getFirst()and getLast() etc. etc.

Iterating is mostly done via for, foreach, while and iterator.


The question's unclear.

The Collection object is the Collection itself. There aren't many ways of getting it other than by its reference.

An object inside the collection can be accessed by get methods and iterators. If you know the internal structure, you can directly access them (as with ArrayList).


What information are you using to find the object? If you have a key, you can use a Map to find an Object. This can be the most efficient and simplest way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号