将对象添加到指定的对象数组

时间:2016-04-12 18:23:53

标签: java arrays object methods constructor

我正在尝试将一个Inv对象添加到java中的InvTrans数组“widget”中。我有InvTrans类中私有数组的构造函数,Invt类中Inv实例的构造函数,以及接受Inv实例的InvTrans对象数组(我想我正在使用适当的词汇表)。我的困境是我想弄清楚我是否将它添加到数组中,但是我很难在数组中显示内容。

public class InvTrans

{
    // variable for a counter in InvTrans Obj.
    private int InvTransIndex = 0;
    private Inv[] transactionArray;

    // Constructor for InvTrans array.
    public InvTrans() {
        this.transactionArray = new Inv[100];
    }

    public static void main(String args[]) {

        InvTrans widget = new InvTrans();

        Inv order1 = new Inv("March 5th, 2016", "Received", 20, 0001, 2.10, 2.20);
        Inv order2 = new Inv("March 6th, 2016", "Received", 100, 0002, 2.10, 2.50);
        Inv order3 = new Inv("March 7th, 2016", "Received", 100, 0003, 2.10, 2.50);
        Inv order4 = new Inv("March 12th, 2016", "Sold", 140, 0004, 2.40, 2.60);

        widget.addLine(order1);
        order1.display();
    }

    public void addLine(Inv a) {
        transactionArray[InvTransIndex] = a;
        InvTransIndex++;
    }

    // Method to add an inventory object to the array.
    public boolean setTransactionLine(Inv i) {
        transactionArray[InvTransIndex] = i;
        InvTransIndex = InvTransIndex + 1;
        return true;
    }
}

// Class Inv (Inventory) contains a constructor for a part and a display method.
class Inv {
    /*
     * Need a constructor which will hold the fields necessary for our Inventory
     * Tracker. Need: a) Date - Date transaction occurred. b) Units - Number of
     * items added or subtracted from inventory. c) Type - Description of
     * transaction. Sale, Receipt, Adjustment. d) Reference Number. e) Cost per
     * Unit - price paid for each unit in inventory. Unused sales. f) Price per
     * unit - What each unit was sold for. Unused receipts.
     */
    String date, type;
    int units, referenceNumber;
    double costPerUnit, pricePerUnit;

    Inv(String d, String t, int u, int r, double c, double p) {
        date = d;
        type = t;
        units = u;
        referenceNumber = r;
        costPerUnit = c;
        pricePerUnit = p;
    }

    public void display() {
        System.out.println(this.date + "\t" + this.type + "\t" + this.units + "\t\t\t\t\t" + this.referenceNumber
                + "\t\t\t\t\t" + this.costPerUnit + "\t\t\t" + this.pricePerUnit);
    }
}

1 个答案:

答案 0 :(得分:0)

这是列表有用的地方。在Java中,使用了两种主要类型的列表:ArrayListLinkedList

我不会详细讨论差异,但是对于你,因为你要使用堆栈数据结构, ArrayLists是完美的,因为在幕后,你做的完全一样正试图编码;增加数组的大小并将最后一个索引设置为要添加的对象。

如何使用它:

而不是创建Inv[]数组。做这个: ArrayList<Inv> transactions = new ArrayList<Inv>();

现在,添加交易很简单,只需这样做: transactions.add(order1);

你去吧!

要访问列表条目,您可以使用transactions.get(int index);,也可以像在数组中一样在foreach循环中使用它们。