How to count the number of occurrences of an element in a List

后端 未结 22 1194
一生所求
一生所求 2020-11-22 12:25

I have an ArrayList, a Collection class of Java, as follows:

ArrayList animals = new ArrayList();
animals.add(\"bat\         


        
22条回答
  •  孤街浪徒
    2020-11-22 12:30

    This shows, why it is important to "Refer to objects by their interfaces" as described in Effective Java book.

    If you code to the implementation and use ArrayList in let's say, 50 places in your code, when you find a good "List" implementation that count the items, you will have to change all those 50 places, and probably you'll have to break your code ( if it is only used by you there is not a big deal, but if it is used by someone else uses, you'll break their code too)

    By programming to the interface you can let those 50 places unchanged and replace the implementation from ArrayList to "CountItemsList" (for instance ) or some other class.

    Below is a very basic sample on how this could be written. This is only a sample, a production ready List would be much more complicated.

    import java.util.*;
    
    public class CountItemsList extends ArrayList { 
    
        // This is private. It is not visible from outside.
        private Map count = new HashMap();
    
        // There are several entry points to this class
        // this is just to show one of them.
        public boolean add( E element  ) { 
            if( !count.containsKey( element ) ){
                count.put( element, 1 );
            } else { 
                count.put( element, count.get( element ) + 1 );
            }
            return super.add( element );
        }
    
        // This method belongs to CountItemList interface ( or class ) 
        // to used you have to cast.
        public int getCount( E element ) { 
            if( ! count.containsKey( element ) ) {
                return 0;
            }
            return count.get( element );
        }
    
        public static void main( String [] args ) { 
            List animals = new CountItemsList();
            animals.add("bat");
            animals.add("owl");
            animals.add("bat");
            animals.add("bat");
    
            System.out.println( (( CountItemsList )animals).getCount( "bat" ));
        }
    }
    

    OO principles applied here: inheritance, polymorphism, abstraction, encapsulation.

提交回复
热议问题