2

How to add a generic object to list in java?

Currently, I have two classes doing the same function and would like to integrate them together

public class MyClass1 {
    private List<Object1> myList = new ArrayList<>();

    public void addList(Object1 o) {
        myList.add(o);
    }
} 

public class MyClass2 {
    private List<Object2> myList = new ArrayList<>();

    public void addList(Object2 o) {
        myList.add(o);
}
} 

something like

public class MyClass {
    private List<Object> myList = new ArrayList<>();

    public void addList(Object o) {
        myList.add(o);
    }
} 

3 Answers 3

3

You could make your own class generic:

public class MyClass<T> {
    private List<T> myList = new ArrayList<>();

    public void addList(T o) {
        myList.add(o);
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

1

You can make both classes Object1 and Object2 implement the same interface 'ObjInterface'

public class MyClass {
    private List<ObjInterface> myList = new ArrayList<>();

    public void addList(ObjInterface o) {
        myList.add(o);
    }
}

Comments

1

If you want the class to contain only Object1 or only Object2 and never anything else, you can combine the other two answers:

interface ObjInterface {
    // may be empty
}

public class MyClass<T extends ObjInterface> {
    private List<T> myList = new ArrayList<>();

    public void addList(T o) {
        myList.add(o);
    }
}

MyClass<Object1> object1only = new MyClass<>();
MyClass<Object2> object2only = new MyClass<>();

and add implements ObjInterface to the definitions of Object1 and Object2.

If you add methods common to both classes to ObjInterface, you can call those methods on the T objects in MyClass, since they're guaranteed to be a subclass of ObjInterface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.