簡體   English   中英

將對象添加到指定的對象數組

[英]Adding an object to a specified array of objects

我試圖在Java中將Inv對象添加到我的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);
    }
}

這是列表有用的地方。 在Java中,使用了2種主要的列表類型: ArrayListLinkedList

我不會詳細介紹它們之間的差異,但是對您來說,由於您將使用堆棧數據結構,因此ArrayLists是完美的,因為在幕后,您正在做與嘗試編寫的代碼完全相同的事情。 增加數組的大小並為要添加的對象設置最后一個索引。

如何使用它:

而不是創建Inv[]數組。 這樣做: ArrayList<Inv> transactions = new ArrayList<Inv>();

現在,添加事務很容易,只需執行以下操作: transactions.add(order1);

你去!

要訪問列表條目,可以使用transactions.get(int index); 您也可以像數組一樣在foreach循環中使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM