java - 我怎样才能把 'group'自定义类放在一起呢?

标签 java android class

我有一些自定义类,其中包含有关 RecyclerView 中不同 View 类型的信息。 ,如标题、描述等(虽然每个类都有不同的变量)。我想将这些类添加到 ArrayList ,但我不希望它成为通用的(对象?)ArrayList ,我想确保只能放入我的自定义类。现在我可以通过使用 setter 和 getter 为它创建另一个类来做到这一点,并做一些检查,但我宁愿有类似 ArrayList<CustomGroup> 的东西, 其中CustomGroup可以是 CustomClass1 中的任何一个, CustomClass2等...这可能吗?如果可能,我该怎么做?

例子:

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);

最佳答案

我建议为此使用一个界面。您可以将接口(interface)用作“标签”,其中接口(interface)基本上只定义您希望列表中允许的类实现它。但是,在您的情况下,您可以让接口(interface)定义 String 和 int 属性。

未指定任何内容的接口(interface)“标签”

public interface ICustomClassInterface {

}

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

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

只有实现接口(interface)的类才能添加到列表中。但是,您的问题是您将通过这个没有定义任何内容的接口(interface)访问它们,即您需要弄清楚它是什么类型。

理想情况下,您可以重构您的类,使其具有在抽象类中定义或在接口(interface)中指定的通用功能,这样您就无需关心实际类型是什么。

定义了所需属性的接口(interface)

public interface ICustomClassInterface {
    String FieldA;
    int FieldB;
}

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

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

关于java - 我怎样才能把 'group'自定义类放在一起呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032926/

相关文章:

java - 声明 createEntityManagerFactory 的最佳方式

android - 如何在 Android Studio 中复制和重命名项目

php - 意外的响应代码 503 (Android Studio)

c++ - 创建带有和不带有 new 关键字的 C++ 对象

java - Java 中类的“final”修饰符

函数的 Javascript 类继承

java - Selenium Java Firefox 驱动程序 - Cookie

java - 1 v.add vector java 中的 2 个元素

Android:使用目标 SDK?

java - Log4j2 - 日期无法以新格式工作