Skip to content
Advertisement

Tag: collections

Java: Get first item from a collection

If I have a collection, such as Collection<String> strs, how can I get the first item out? I could just call an Iterator, take its first next(), then throw the Iterator away. Is there a less wasteful way to do it? Answer Iterables.get(yourC, indexYouWant) Because really, if you’re using Collections, you should be using Google Collections.

What are Reified Generics? How do they solve Type Erasure problems and why can’t they be added without major changes?

I’ve read Neal Gafter’s blog on the subject and am still unclear on a number of points. Why is it not possible to create implementations of the Collections API that preserve type information given the current state of Java, the JVM and existing collections API? Couldn’t these replace the existing implementations in a future version of Java in a way

Why doesn’t java.util.Set have get(int index)?

I’m sure there’s a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get() method? It seems that sets are great for putting things into, but I can’t find an elegant way of retrieving a single item from it. If I know I want the first item, I can use set.iterator().next(), but

When to use LinkedList over ArrayList in Java?

I’ve always been one to simply use: I use the interface as the type name for portability, so that when I ask questions such as this, I can rework my code. When should LinkedList be used over ArrayList and vice-versa? Answer Summary ArrayList with ArrayDeque are preferable in many more use-cases than LinkedList. If you’re not sure — just start with

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

We all know you can’t do the following because of ConcurrentModificationException: But this apparently works sometimes, but not always. Here’s some specific code: This, of course, results in: Even though multiple threads aren’t doing it. Anyway. What’s the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception? I’m

Advertisement