List vs Map in Java

前端 未结 9 1830
灰色年华
灰色年华 2020-12-02 23:29

I didnt get the sense of Maps in Java. When is it recommended to use a Map instead of a List?

thanks in advance,

nohereman

相关标签:
9条回答
  • 2020-12-02 23:54

    When you want to map instead of list. The names of those interfaces have meaning, and you shouldn't ignore it.

    Use a map when you want your data structure to represent a mapping for keys to values. Use a list when you want your data to be stored in an arbitrary, ordered format.

    0 讨论(0)
  • 2020-12-03 00:01

    I thinks its a lot the question of how you want to access your data. With a map you can "directly" access your items with a known key, in a list you would have to search for it, evan if its sorted.

    Compare:

    List<MyObject> list = new ArrayList<MyObject>();
    //Fill up the list
    // Want to get object "peter"
    for( MyObject m : list ) {
     if( "peter".equals( m.getName() ) {
        // found it
     }
    }
    

    In a map you can just type

    Map<String, MyObject> map = new HashMap<String, MyObject>();
    // Fill map
    MyObject getIt = map.get("peter");
    

    If you have data to process and need to do it with all objects anyway, a list is what you want. If you want to process single objects with well known key, a map is better. Its not the full answer (just my 2...) but I hope it might help you.

    0 讨论(0)
  • 2020-12-03 00:05

    Maps store data objects with unique keys,therefore provides fast access to stored objects. You may use ConcurrentHashMap in order to achieve concurrency in multi-threaded environments. Whereas lists may store duplicate data and you have to iterate over the data elements in order to access a particular element, therefore provide slow access to stored objects. You may choose any data structure depending upon your requirement.

    0 讨论(0)
提交回复
热议问题