KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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); } } }
Tags (comma-separated)
Save Edits
Cancel