亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將對象添加到列表

將對象添加到列表

素胚勾勒不出你 2021-09-03 17:43:56
這可能是一個非常簡單的解決方案,但我剛剛開始學習 Java。我想將每個實例化的產品添加到產品列表中。有沒有辦法在不修改訪問修飾符的情況下解決這個問題?public class Product {    private int id;    private String name;    private float defaultPrice;    private Currency defaultCurrency;    private Supplier supplier;    private static List<Product> productList;    private ProductCategory productCategory;    public Product(float defaultPrice, Currency defaultCurrency, String name) {        this.id = IdGenerator.createID();        this.defaultPrice = defaultPrice;        this.defaultCurrency = defaultCurrency;        this.name = name;    }}
查看完整描述

3 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

就像Peter Lawrey在Mureinik's answer的評論部分提到的那樣,static在 POJO 中擁有一個集合并不是最好的解決方案。


我建議使用簡單的外觀。這將列表存在限制為外觀生命并且不包括 POJO 中集合的邏輯。


public class FacadeProduct {


    private List<Product> cacheProduct = new ArrayList<>();


    public Product createProduct(float defaultPrice, Currency defaultCurrency, String name){

        Product p = new Product(defaultPrice, defaultCurrency, name);

        cacheProduct.add(p);

        return p;

    }

}

這將非常簡單易用。


public static void main(String ars[]){

    {

        FacadeProduct f = new FacadeProduct();

        {

            Product p1 = f.createProduct(1f, null, "test1");

            Product p2 = f.createProduct(1f, null, "test2");

            Product p3 = f.createProduct(1f, null, "test3");

            // Here, the list have 3 instances in it

        }

        // We lose the p1, p2, p3 reference, but the list is still holding them with f.

    }

    //Here, we lose the f reference, the instances are all susceptible to be collected by the GC. Cleaning the memory

}


查看完整回答
反對 回復 2021-09-03
?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

更改初始化行

private static List<Product> productList;

private static List<Product> productList = new LinkedList<>();

添加productList.add(this)為構造函數的最后一行。

因此,每次調用 Product 構造函數時,它都會將此實例添加到靜態列表中。


查看完整回答
反對 回復 2021-09-03
  • 3 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號