Can someone please provide an example of creating a Java ArrayList
and HashMap
on the fly? So instead of doing an add()
or put()
, actually supplying the seed data for the array/hash at the class instantiation?
To provide an example, something similar to PHP for instance:
$array = array (3, 1, 2); $assoc_array = array( 'key' => 'value' );
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.
HashMap is faster than HashSet because the values are associated to a unique key. In HashSet , member object is used for calculating hashcode value which can be same for two objects so equals() method is used to check for equality.
ArrayMap is a map (key -> value pairs). ArrayList is a list (a sequence of items). The JavaDoc tells you. It's generally slower but aims to reduce the memory footprint.
List<String> list = new ArrayList<String>() { { add("value1"); add("value2"); } }; Map<String,String> map = new HashMap<String,String>() { { put("key1", "value1"); put("key2", "value2"); } };
A nice way of doing this is using List.of()
and Map.of()
(since Java 8):
List<String> list = List.of("A", "B", "C"); Map<Integer, String> map = Map.of(1, "A", 2, "B", 3, "C");
Java 7 and earlier may use Google Collections:
List<String> list = ImmutableList.of("A", "B", "C"); Map<Integer, String> map = ImmutableMap.of( 1, "A", 2, "B", 3, "C");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With