Search code examples
javaserializable

Arraylist of two types that implement java.io.Serializable


For example I have:

    public class Class1 implements Serializable {
       private static final long serialVersionUID = 1L;
       private int a;
       private int b;

       /*Getters and setters here*/
       public int getA();
    }

    public class Class2 implements Serializable {
       private static final long serialVersionUID = 1L;
       private int a;
       private int b;

       /*Getters and setters here*/
       public int getA();
    }

Now I want to make an ArrayList of those two types. This is what I'm trying:

List<Serializable> list= new ArrayList<Serializable>();

I have a method that returns Serializable, which returns the object in the list:

  public Serializable get(int i)
{
    return list.get(i);
}

However, when I'm trying to use the getter method from the two classes above( something like list.get(0).getA()) , there's an error saying the getA() method is not defined for Serializable. Am I missing something simple here? What should I use for the return type of the method above in order to use the getter method? Thanks.


Solution

  • You are returning a Serializable object, not a Class1 object. There are two routes to doing this, but I recommend the latter:

    Serializable s = list.get(1);
    if (s instanceof Class1) {
        Class1 clazz = (Class1) s;
        clazz.getA();
    } //etc...
    

    Or, using a common interface:

    public interface YourClass extends Serializable {
    
        public int getA();
    
    }
    
    //...
    
    List<YourClass> list = new ArrayList<>();