casting Arrays.asList causing exception: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

For me (using Java 1.6.0_26), the first snippet gives the same exception as the second one. The reason is that the Arrays.asList(..) method does only return a List, not necessarily an ArrayList. Because you don’t really know what kind (or implementation of) of List that method returns, your cast to ArrayList<String> is not safe. The … Read more

Arrays.asList() of an array

Let’s consider the following simplified example: public class Example { public static void main(String[] args) { int[] factors = {1, 2, 3}; ArrayList<Integer> f = new ArrayList(Arrays.asList(factors)); System.out.println(f); } } At the println line this prints something like “[[I@190d11]” which means that you have actually constructed an ArrayList that contains int arrays. Your IDE and … Read more

Java 8 lambda create list of Strings from list of custom class objects

You need to collect your Stream into a List: List<String> adresses = users.stream() .map(User::getAdress) .collect(Collectors.toList()); For more information on the different Collectors visit the documentation. User::getAdress is just another form of writing (User user) -> user.getAdress() which could as well be written as user -> user.getAdress() (because the type User will be inferred by the … Read more

Java ArrayList of ArrayList

You are adding a reference to the same inner ArrayList twice to the outer list. Therefore, when you are changing the inner list (by adding 300), you see it in “both” inner lists (when actually there’s just one inner list for which two references are stored in the outer list). To get your desired result, … Read more

How does memory allocation of an ArrayList work?

If JVM is not able to allocate requested amount of memory it’ll throw OutOfMemoryError That’s it. Actually JVM memory allocation has only two possible outcomes: Application is given requested amount of memory. JVM throws OutOfMemoryError. There is no intermediate options, like some amount of memory is allocated. It has nothing to do with ArrayList, it’s … Read more