Difference between

This question already has answers here: What is PECS (Producer Extends Consumer Super)? (16 answers) Closed 3 years ago. What is the difference between List<? super T> and List<? extends T> ? I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List<? super … Read more

How can I initialise a static Map?

How would you initialise a static Map in Java? Method one: static initialiser Method two: instance initialiser (anonymous subclass) or some other method? What are the pros and cons of each? Here is an example illustrating the two methods: import java.util.HashMap; import java.util.Map; public class Test { private static final Map<Integer, String> myMap = new … Read more

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

We all know you can’t do the following because of ConcurrentModificationException: for (Object i : l) { if (condition(i)) { l.remove(i); } } But this apparently works sometimes, but not always. Here’s some specific code: public static void main(String[] args) { Collection<Integer> l = new ArrayList<>(); for (int i = 0; i < 10; ++i) … Read more

How to directly initialize a HashMap (in a literal way)?

Is there some way of initializing a Java HashMap like this?: Map<String,String> test = new HashMap<String, String>{“test”:”test”,”test”:”test”}; What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some “final/static” values in a map that never change and are known in … Read more

Initialization of an ArrayList in one line

I wanted to create a list of options for testing purposes. At first, I did this: ArrayList<String> places = new ArrayList<String>(); places.add(“Buenos Aires”); places.add(“Córdoba”); places.add(“La Plata”); Then, I refactored the code as follows: ArrayList<String> places = new ArrayList<String>( Arrays.asList(“Buenos Aires”, “Córdoba”, “La Plata”)); Is there a better way to do this? 3 33