Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java proper extension design for a class with a generic collection

Tags:

java

arraylist

Let's say I got classes A,B,C such that B extends A and C also extends A.

Now I got 2 different classes, lets call them MyClassB and MyClassC with a member of ArrayList<B> and ArrayList<C> respectfuly.

Since many actions in MyClassB and MyClassC are the same and are only done on the different type of ArrayList, I wanted to create a new abstract class MyClassA which will have an implementation of the same actions on an ArrayList<A> for both classe, since A is the common part which the actions are the same on.

So I tried creating a method in the new MyClassA class which receives a list as an argument and is supposed to make the action on that list. However, I can't pass an ArrayList<B> to the method where it expects ArrayList<A>.

So what can I do in order to keep the same actions in a different class and not repeat the code in 2 different classes?

like image 403
Yonatan Nir Avatar asked May 25 '15 13:05

Yonatan Nir


People also ask

Why use generic methods?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

What is T type Java?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

Do generics in Java exist in the the Java compiler or the Java Virtual Machine?

Implementation of Language Features Basically, that means that the CLR recognizes the difference between, for example, List<int> and List<String>, whereas the JVM can't (Java implemented Generics as part of the compiler).


2 Answers

class MyClassA<T extends A>
{
    ArrayList<T> list;

    public MyClassA(ArrayList<T> list)
    {
        this.list = list;

...

class MyClassB extends MyClassA<B>
{
    MyClassB(ArrayList<B> list)
    {
         super(list);
like image 171
ZhongYu Avatar answered Nov 08 '22 03:11

ZhongYu


Try with generics:

public class MyClassA<T extends A> {
    public void doSomething(ArrayList<T> list) {
        // do something
    }
}

Now MyClassB and MyClassC can inherit from it and you can work with the list normally.

like image 20
Balduz Avatar answered Nov 08 '22 03:11

Balduz