Usage of ArrayList instead of Map in OkHttp

Viewed 305

I was going through the source of the Header class in okhttp3; For storing headers and the corresponding values, an ArrayList is used; So for first key 0, it's value will be at 1 and so on...

This is the method that does this work:

final List<String> namesAndValues = new ArrayList<>(20);

Builder addLenient(String name, String value) {
      namesAndValues.add(name);
      namesAndValues.add(value.trim());
      return this;
    }

So I just want to know the reason behind using an ArrayList instead of a Map like data structure

1 Answers

Header usually are presented with multimap Map<String,List<String>>

It seems internally they have decided to use a single list which serves the same purpose. Initially was even an array. I would say it is more a develop preference, as this is internal code and it is hidden for the audience.

Possible could be to save some memory instead of using multimap and less garbage - imagine having 10 headers it will be a map with 10 lists + the items inside.(Usually these are created on every http request)

Headers class should have also a method toMultimap

Related