LeoParis
LeoParis

Reputation: 1

How to give a List of any object as parameter in Java?

I have several classes that are doing the same thing : iterates over a List in an object, and add each items in a private field. I have two objects : MyCustomObject, that have several fields, and ResultOfQuery, where it has a field called data that is a List<Map<String, Object>>.

For example:

private List<MyCustomObject> myCustomObjectList = new LinkedList();

public void setMyCustomObject (ResultOfQuery resultOfQuery){
    ObjectMapper objectMapper = new ObjectMapper();
    if(resultOfQuery!= null) {
        for (Map<String, Object> map : resultOfQuery.getData()) {
            myCustomObjectList.add(objectMapper.convertValue(map, 
                    MyCustomObject.class));
        }
    }

The problem is that I have other classes that does the exact same method, but with another object instead of MyCustomObject.

So I thought that a good idea would be that all of these classes should extends a class that contains this method, and as a parameter it should take first a resultOfQuery, then a list of any objects, and then a Class. Does it sounds good, or there is a better way to achieve this?

Also, how to give a list of any object ? I tried List<?>, but this shows me the following error :

Error at list add line

Upvotes: 0

Views: 1798

Answers (2)

pirho
pirho

Reputation: 12215

You can achieve type safety with generics and inheritance. If you declare a base class having the common stuff like:

public class BaseClass<T> {
    
    private List<T> tList = new LinkedList<>();
    private final Class<T> classT;
    
    public BaseClass(Class<T> classT) {
        this.classT = classT;
    }
    
    public void setObject (ResultOfQuery resultOfQuery){
        ObjectMapper objectMapper = new ObjectMapper();
        if(resultOfQuery!= null) {
            for (Map<String, Object> map : resultOfQuery.getData()) {
                tList.add(objectMapper.convertValue(map, classT));
            }
        }
    } 
}

Then it is easy to extend it for each different type, like:

public class MyCustomObjectExtendedClass extends BaseClass<MyCustomObject> {
    public MyCustomObjectExtendedClass() {
        super(MyCustomObject.class);
    }
}

I have renamed stuff because it was decoupled from the MyCustomObject.

Upvotes: 1

Antaaaa
Antaaaa

Reputation: 233

You can use private List myCustomObjectList = new LinkedList();

Instantiating a class using a raw type (i.e. without a type parameter, as in List list = new ArrayList(3)), is something you shouldn't do, as it is less type-safe, and is only allowed for backwards compatibility.

Link: Java Generics List and ArrayList with and without Parameters

Upvotes: 0

Related Questions