0

I basically have my own custom list which has a bunch of functionality but since I am manipulating the same kinds of lists I wanted to extend this custom list with a defined type and want to be able to use the parent functions and return the child type.

Example:

//Object within the list
public class ChildObject {

    private string name;

    // getters, setters, methods, etc.
}


// Parent custom list
public class ParentList<T> extends ArrayList<T> {

    public ParentList<T> filter(Predicate<T> predicate) {
        Collector<T, ?, List<T>> collector = Collectors.toList();

        List<T> temp = this.stream().filter(predicate).collect(collector);

        this.clear();
        this.addAll(temp);

        return this;
    }
}

// Extended custom list with predefined type
public class ChildList extends ParentList<ChildObject> {

    // other methods
}

// implementation
public static void main(String[] args) {

    ChildObject a = new ChildObject("Alice");
    ChildObject b = new ChildObject("Bob");

    ChildList filterList = new ChildList();
    filterList.add(a);
    filterList.add(b);

    filterList.filter(c -> childObject.getName().equals("Alice"));
}

It would be really nice if this is possible but feel free to chime in whether this is doable, practical, or have any thoughts on performance issues or bad practices.

  • It's a fairly common pattern. You need to add a generic parameter: `ParentList>`, `public S filter(...) {... return (S)this;}`, `ChildList extends ParentList`. Note that this is not entirely typesafe (hence the unsafe cast), as it's possible for child classes to specify the wrong type. – shmosel Aug 17 '17 at 23:57
  • I have seen that pattern but never looked into the functionality. I will have to look into that more. Thanks! – ofgodsandmythos Aug 18 '17 at 00:02

1 Answers1

0

I did figure out a solution but I want to know if their is any way to make it work without the following solution:

// Extended custom list with predefined type
public class ChildList extends ParentList<ChildObject> {

    public ChildList filter(Predicate<ChildObject> predicate) {
        super.filter(predicate);

        return this;
    }

    // other methods
}