Search code examples
javaandroidarraylistserver-communication

Java class, Arraylist with multiple types


i'm new to Android & Java and have a question regarding my server-app-communication. My server always returns a JSON output with "Code", "Message" and "Data". Like this:

e.g: {"code":200,"msg":"success","data":[{"track_id":123},{"track_id":124},{"track_id":125}]}
e.g: {"code":200,"msg":"success","data":[{"type":"car","length":100},{"type":"train","length":500},{"type":"foot","length":3}]}

I want to use a class like this to work with the data:

public class ServerResponse {
    private int code;
    private String msg;
    private List<> data;
}

But here is my problem. I don't want to give a specific type like "car", "login" etc. to the List. Depending on my request I want to create the ServerResponse-class with a List-Type "car", another with List-Type "Locations" etc.

Is there a way to use the class ServerResponse with multiple type of ArrayLists or do I have to copy this class several times for every list-type I'd like to use?

I'm sorry if there's already a solution somewhere here, but I do not know what I have to search for. And for what I searched, I couldn't find a propper solution.

Best regards Michael


Solution

  • Look into Java Generic Types.

    public class ServerResponse<T> { 
        private int code;
        private String msg;
        private List<T> data;
    } 
    

    T can be whatever type you want it to be, so your list will then be of that type. Then your getter/setter methods can return or accept type T.

    Now let us assume your response was for a Car object. You would do this

    private ServerResponse<Car> mCarResponse = new ServerResponse<>();
    

    Now you can put a method inside your ServerResponse class like this.

    public class ServerResponse<T> { 
        private int code;
        private String msg;
        private List<T> data;
    
        public List<T> getResponseObjectList(){
            return data;
        }
    } 
    

    You will now get a List<Car> object.