简体   繁体   English

将项目“递归”添加到 ArrayList

[英]Add item to ArrayList "recursively"

I have an static ArrayList which I can only access from a class ("Sale").我有一个静态 ArrayList,我只能从一个类(“Sale”)访问它。 In that ArrayList I want to add items of the same class.在那个 ArrayList 中,我想添加同一类的项目。 How can I add them from the constructor?如何从构造函数添加它们?

I've done it this way and it doesn't work:我已经这样做了,但它不起作用:

public class Sale{
     private static ArrayList<Sale> sales;
     private Buyer buyer;
     private Item item;

     public Sale(Buyer buyer, Item item){
          this.buyer=buyer;
          this.item=item;
          sales.add(this);
     }
.....

Thanks in advance, I'm starting programming in Java.提前致谢,我开始用 Java 编程。

You haven't initialized your sales ArrayList.您尚未初始化您的sales ArrayList。 You can do so by changing你可以通过改变来做到这一点

private static ArrayList<Sale> sales;

to something like

private static ArrayList<Sale> sales = new ArrayList<Sale>();

or using the diamond operator <> (Java 7+) like使用菱形运算符<> (Java 7+) 之类的

private static ArrayList<Sale> sales = new ArrayList<>();

But I would suggest you program to the List interface .但我建议你编程到List界面 Something like就像是

private static List<Sale> sales = new ArrayList<>();

Another possible option is a static initializer , like另一种可能的选择是静态初始化程序,例如

private static List<Sale> sales;
static {
    sales = new ArrayList<>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM