18

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 below.

This seems sensible to me, but I'm very new to Java and I see other questions which discourage extending ArrayList, for example Extending ArrayList and Creating new methods. I don't know enough Java to understand the objections.

In my prior attempt, I ending up creating a number of methods in ThingContainer that were essentially pass-throughs to ArrayList, so extending seemed easier.

Is there a better way to do what I'm trying to do? If so, how should it be implemented?

import java.util.*;

class Thing {
    public String name;
    public int amt;

    public Thing(String name, int amt) {
        this.name = name;
        this.amt = amt;
    }

    public String toString() {
        return String.format("%s: %d", name, amt);
    }

    public int getAmt() {
        return amt;
    }
}

class ThingContainer extends ArrayList<Thing> {
    public void report() {
        for(int i=0; i < size(); i++) {
            System.out.println(get(i));
        }
    }

    public int total() {
        int tot = 0;
        for(int i=0; i < size(); i++) {
            tot += ((Thing)get(i)).getAmt();
        }
        return tot;
    }

}

public class Tester {
    public static void main(String[] args) {
        ThingContainer blue = new ThingContainer();

        Thing a = new Thing("A", 2);
        Thing b = new Thing("B", 4);

        blue.add(a);
        blue.add(b);

        blue.report();
        System.out.println(blue.total());

        for (Thing tc: blue) {
            System.out.println(tc);
        }
    }
}
Community
  • 1
  • 1
foosion
  • 7,619
  • 25
  • 65
  • 102
  • The answer from Jon Skeet includes "I wouldn't extend ArrayList<> unless I really had to, preferring composition over inheritance" Or "As many other have said, yes, you can extend class ArrayList, but it is not something that you should normally do; it is not considered good practice in Java." from http://stackoverflow.com/questions/4779173/can-you-extend-arraylist-in-java. However, from your and other answers, I appear to be misinterpreting. – foosion Nov 11 '11 at 19:06
  • Personally, I tend to avoid subclassing JDK classes, because there might be a change in implementation that I can't control, or that breaks something in my extension that I wasn't aware of--there are occasionally subtle "gotchas" when relying on superclass behavior that we don't always think about, or *can't* think about if we don't have implementation details. – Dave Newton Nov 11 '11 at 19:38
  • @DaveNewton, wouldn't that problem equally apply to using JDK classes? – foosion Nov 12 '11 at 11:03
  • You mean just using them without subclassing them? – Dave Newton Nov 12 '11 at 13:37
  • That's different, because then all usage of the class's methods are controlled by the class. I'll add a small blurb in my answer within a few minutes. – Dave Newton Nov 12 '11 at 15:54
  • Added more composition-over-inheritance ammo. – Dave Newton Nov 12 '11 at 16:06

3 Answers3

11

Nothing in that answer discourages extending ArrayList; there was a syntax issue. Class extension exists so we may re-use code.

The normal objections to extending a class is the "favor composition over inheritance" discussion. Extension isn't always the preferred mechanism, but it depends on what you're actually doing.

Edit for composition example as requested.

public class ThingContainer implements List<Thing> { // Or Collection based on your needs.
    List<Thing> things;
    public boolean add(Thing thing) { things.add(thing); }
    public void clear() { things.clear(); }
    public Iterator<Thing> iterator() { things.iterator(); }
    // Etc., and create the list in the constructor
}

You wouldn't necessarily need to expose a full list interface, just collection, or none at all. Exposing none of the functionality greatly reduces the general usefulness, though.

In Groovy you can just use the @Delegate annotation to build the methods automagically. Java can use Project Lombok's @Delegate annotation to do the same thing. I'm not sure how Lombok would expose the interface, or if it does.

I'm with glowcoder, I don't see anything fundamentally wrong with extension in this case--it's really a matter of which solution fits the problem better.

Edit for details regarding how inheritance can violate encapsulation

See Bloch's Effective Java, Item 16 for more details.

If a subclass relies on superclass behavior, and the superclass's behavior changes, the subclass may break. If we don't control the superclass, this can be bad.

Here's a concrete example, lifted from the book (sorry Josh!), in pseudo-code, and heavily paraphrased (all errors are mine).

class CountingHashSet extends HashSet {
    private int count = 0;
    boolean add(Object o) {
        count++;
        return super.add(o);
    }
    boolean addAll(Collection c) {
        count += c.size();
        return super.addAll(c);
    }
    int getCount() { return count; }
}

Then we use it:

s = new CountingHashSet();
s.addAll(Arrays.asList("bar", "baz", "plugh");

And it returns... three? Nope. Six. Why?

HashSet.addAll() is implemented on HashSet.add(), but that's an internal implementation detail. Our subclass addAll() adds three, calls super.addAll(), which invokes add(), which also increments count.

We could remove the subclass's addAll(), but now we're relying on superclass implementation details, which could change. We could modify our addAll() to iterate and call add() on each element, but now we're reimplementing superclass behavior, which defeats the purpose, and might not always be possible, if superclass behavior depends on access to private members.

Or a superclass might implement a new method that our subclass doesn't, meaning a user of our class could unintentionally bypass intended behavior by directly calling the superclass method, so we have to track the superclass API to determine when, and if, the subclass should change.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 3
    I like your last line, "Extensions isn't always the preferred mechanism". That says it all. When it comes to something like this, where you have say `java.util.List` to compose, if you still want your class to extend it, you have to make a member `List` and then make, what 20 other boilerplate methods? So yes, normally I agree that composition is better than inheritance. But I think in this case inheritance is the way to go. – corsiKa Nov 11 '11 at 19:04
  • I don't understand how I'd implement composition here. Please elaborate. Or are you saying the normal objection does not apply here? – foosion Nov 11 '11 at 19:08
  • @foosion To composite, you'd create the app-specific class, give it a `List` instance variable, and delegate list-like functionality straight to the list. I'll put a tiny example in the answer. – Dave Newton Nov 11 '11 at 19:15
  • @DaveNewton, aha. That's actually how I started. Then I thought extension would be better because I wouldn't need to implement add, clear, etc. methods. Extension would give me them for free. – foosion Nov 11 '11 at 19:34
0

I don't think extending arrayList is necessary.

public class ThingContainer {

    private ArrayList<Thing> myThings;

    public ThingContainer(){
        myThings = new ArrayList<Thing>();
    }

    public void doSomething(){
         //code
    }

    public Iterator<Thing> getIter(){
        return myThings.iterator();
    }
}

You should just wrap ArrayList in your ThingContainer class. ThingContainer can then have any processing methods you need. No need to extend ArrayList; just keep a private member. Hope this helps.

You may also want to consider creating an interface that represents your Thing Class. This gives you more flexibility for extensibility.

public Interface ThingInterface {
   public void doThing();
}

...

public OneThing implements ThingInterface {
   public void doThing(){
        //code
   }
}

public TwoThing implements ThingInterface {
   private String name;
   public void doThing(){
        //code
   }
}
b3bop
  • 3,373
  • 2
  • 17
  • 17
  • 3
    In this case, if I want add, addall, clear, get, remove, etc. from ArrayList it seems I'd need to create corresponding methods, while extending lets me use these from ArrayList without further action. Am I missing something? – foosion Nov 11 '11 at 19:30
  • how it will be possible to add `Thing` in `ThingContainer`? :P – Kowser Nov 11 '11 at 19:32
0

Here is my suggestion:

interface ThingStorage extends List<Thing> {
    public int total();
}

class ThingContainer implements ThingStorage {

    private List<Thing> things = new ArrayList<Thing>();

    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.

Kowser
  • 8,123
  • 7
  • 40
  • 63