Extending a java ArrayList

后端 未结 3 1737
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 15:14

I\'d like to extend ArrayList to add a few methods for a specific class whose instances would be held by the extended ArrayList. A simplified illustrative code sample is be

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 15:54

    Here is my suggestion:

    interface ThingStorage extends List {
        public int total();
    }
    
    class ThingContainer implements ThingStorage {
    
        private List things = new ArrayList();
    
        public boolean add(Thing e) {
            return things.add(e);
        }
    
        ... remove/size/... etc     
    
        public int total() {
            int tot = 0;
            for(int i=0; i < size(); i++) {
                tot += ((Thing)get(i)).getAmt();
            }
            return tot;
        }
    
    }
    

    And report() is not needed actually. toString() can do the rest.

提交回复
热议问题