Rule of thumb for choosing an implementation of a Java Collection?

前端 未结 11 1513
执念已碎
执念已碎 2020-11-29 16:06

Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?

For example, generally why or i

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 16:47

    Use Map for key-value pairing

    For key-value tracking, use Map implementation.

    For example, tracking which person is covering which day of the weekend. So we want to map a DayOfWeek object to an Employee object.

    Map < DayOfWeek , Employee > weekendWorker = 
        Map.of( 
            DayOfWeek.SATURDAY , alice ,
            DayOfWeek.SUNDAY , bob
        )
    ;
    

    When choosing one of the Map implementations, there are several aspects to consider. These include: concurrency, tolerance for NULL values in key and/or value, order when iterating keys, tracking by reference versus content, and convenience of literals syntax.

    Here is a chart I made showing the various aspects of each of the ten Map implementations bundled with Java 11.

提交回复
热议问题