【问题标题】:specify array list type from an attribute从属性指定数组列表类型
【发布时间】:2020-07-03 09:51:58
【问题描述】:

想象一下我有三个班级

Feedback
Customer
Supplier

现在我有一个仅用于反馈类的分页代码

    public ArrayList<Feedback> generatePage(int currentPage,Class paginator_type)
    {
        int startItem=currentPage*ITEMS_PER_PAGE;
        int numOfData=ITEMS_PER_PAGE;
        ArrayList<Feedback> pageData=new ArrayList<>();

        if (currentPage == LAST_PAGE )
        {
            for(int i=startItem;i<startItem+ITEMS_REMAINING;i++){
                String ss[] = all_data[i].split(" ");
                pageData.add(new Feedback(ss[5],ss[3],ss[4],ss[0]));

            }
        }
        else
        {
            for (int i=startItem;i<startItem+numOfData;i++)
            {
            String ss[] = all_data[i].split(" ");
            pageData.add(new Feedback(ss[5],ss[3],ss[4],ss[0]));

            }

        }
        return pageData;
    }

现在我需要 arraylist 类型来更改要添加到其中的对象类型 我只需要制作一种接受任何类型数组列表的方法,我该怎么做?以及我如何制作一个接受类类型的参数 例如:

调用方法:

makeArrayList(1,Reservation);

方法:

public void makeArrayList(int i , Class class) <- how i can declare the parameter
ArrayList<class> aa = new ArrayList<>();

【问题讨论】:

  • 编写一个接口并让所有三个类都实现它,然后停止关心“可能存在哪些特定类型的类”,而是为该接口编写代码。任何实现它的类现在都可以工作了。
  • @Mike'Pomax'Kamermans 先生,我能解释一下吗?
  • 当然,但不是来自我。看看docs.oracle.com/javase/tutorial/java/IandI/createinterface.html,接口是基本 Java 的一部分,您可能应该从一本好书或教程而不是 Stackoverflow 评论或答案中了解如何使用它们。

标签: java arrays class arraylist


【解决方案1】:

您可以定义一个interface 并在您想要的类或abstract 类中实现并扩展它。

例子

public interface IBase { }

public class Feedback implements IBase {}
public class Customer implements IBase {}
public class Supplier implements IBase {}

并在此方法中将类更改为:

public void makeArrayList(int i , IBase parent)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多