List vs Map in Java

前端 未结 9 1884
灰色年华
灰色年华 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-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 list = new ArrayList();
    //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 map = new HashMap();
    // 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.

提交回复
热议问题