Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6806737
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T19:44:50+00:00 2026-05-26T19:44:50+00:00

I’d like to extend ArrayList to add a few methods for a specific class

  • 0

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);
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T19:44:51+00:00Added an answer on May 26, 2026 at 7:44 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to count the length of a string with PHP. The string
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am trying to render a haml file in a javascript response like so:
I have some data like this: 1 2 3 4 5 9 2 6
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.