Timmiej93 Timmiej93 - 5 months ago 16
Android Question

How can I 'group' custom classes together?

I have some custom classes, which contain information about different viewtypes in a

RecyclerView
, like title, description, etc (there are different variables for each class though). I want to add these classes to an
ArrayList
, but I don't want it to be a generic (Object?)
ArrayList
, I want to make sure only my custom classes can be put in. Now I could do this by making another class for it with a setter and getter, and do some checks, but I'd rather have something like
ArrayList<CustomGroup>
, where
CustomGroup
could be any of
CustomClass1
,
CustomClass2
, etc... Is this possible, and if so, how would I do this?

Example:

public class CustomClass1 {
String title, description;
int amount;

// Getter & Setter
}

public class CustomClass2 {
String errorMessage;
int errorCode;

// Getter & Setter
}

public class CustomClass3 {
String warningName;
double amount;

// Getter & Setter
}

ArrayList<CustomGroup> arrayList = new ArrayList<>();

CustomClass3 customClass3 = new CustomClass3();
// Set values for customClass3

arrayList.add(customClass3);

CustomClass1 customClass1 = new CustomClass1();
// Set values for customClass1

arrayList.add(customClass1);

Answer

I would recommend using an interface for this. You can use interfaces as "tags", where the interface basically defines nothing but the classes you want to allow in the list implement it. In your case, however, you could have the interface define the String and int properties.

Interface "tag" with nothing specified

public interface ICustomClassInterface {

}

public class CustomClass1 implements ICustomClassInterface {
    String title, description;
    int amount;
}

ArrayList<ICustomClassInterface> arrayList = new ArrayList<ICustomClassInterface>();

Only classes that implement the interface can be added to the list. However, your issue here is you will be getting to them through this interface which defines nothing, i.e. you will need to figure out what type it is.

Ideally you would refactor your classes to have the common functionality either defined in an abstract class or specified in an interface, then you don't need to care what the actual type is.

Interface with needed properties defined

public interface ICustomClassInterface {
    String FieldA;
    int FieldB;
}

public CustomClass1 implements ICustomClassInterface {
    String FieldA;
    int FieldB;
}

ArrayList<ICustomClassInterface> arrayList = new ArrayList<ICustomClassInterface>();