简体   繁体   English

将对对象的引用存储在ArrayList中

[英]Storing a reference to the object in ArrayList

Hey everyone i am trying to store the current reference to an arraylist "pl". 大家好,我正在尝试将当前引用存储到arraylist“ pl”。 eg pl.add(this); 例如pl.add(this); for some reason i only get the reference to the last item and none of the previous ones. 由于某种原因,我仅获得对最后一项的引用,而没有任何先前的引用。 The Loop does go through all three items tho. 循环确实通过了所有三个项目。

Below is the code and out put i am getting. 下面是代码,并把我得到。 Can anyone tell me what i am doing wrong thank you for the help in advance. 谁能告诉我我在做什么错,谢谢您的帮助。

       // variables
private String productType;
private String hyperLinkParam;
private ArrayList <ProductList> pl = new ArrayList<ProductList> ();

public ProductList() {

    try {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

       InputStream url = null;
        url = getClass().getResourceAsStream("inventory.xml");


        Document doc = db.parse(url);
        doc.getDocumentElement().normalize();

        // loop through each item
        NodeList items = doc.getElementsByTagName("item"); //Returns a list of elements with the given tag name item
        for (int i = 0; i < items.getLength(); i++)
        {

                Element e = (Element) items.item(i);
                setHyperLinkParam(e.getAttribute("name").toString());
                setProductType(getTextValue(e,"productType"));
                System.out.print(e.getAttribute("name").toString());
                System.out.println(getTextValue(e,"productType"));

                pl.add(this);


         }

          for(int j=0; j < pl.size(); j++){
            System.out.print("getHyperLinkParam: " + pl.get(j).getHyperLinkParam());
            System.out.println("getProductType: " + pl.get(j).getProductType());
          }

Manufacture.java 制造.java

    @WebMethod(operationName = "getProductList")
public ProductList getProductList() {
    try {
        ProductList productlist = new ProductList();
        if(productlist == null){
            return null;
        }else{
            return productlist;
        }
    } catch(Exception e){
        System.out.println("error: " + e.getMessage());
        return null;
    }
}

index.jsp index.jsp

    <%
try {
org.soen487.supplychain.manufacturer.Manufacture_Service service = new org.soen487.supplychain.manufacturer.Manufacture_Service();
org.soen487.supplychain.manufacturer.Manufacture port = service.getManufacturePort();
// TODO process result here
org.soen487.supplychain.manufacturer.ProductList result = port.getProductList();
out.println("Result = "+result);

} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>

This is the problem: 这就是问题:

pl.add(this);

You're adding the same reference ( this ) again and again. 您一次又一次地添加相同的引用( this )。 The value of this is just a reference to the "current" object - and you're modifying the contents of that object in the loop. this仅仅 “当前”对象的引用-你正在修改的循环,对象的内容。

In each iteration of the loop you should create a new, separate object, set the properties on that object, and then add a reference to that object to the list. 在循环的每次迭代中,您应该创建一个新的单独的对象,在对象上设置属性,然后将对该对象的引用添加到列表中。

It's slightly odd that you'd be adding this to the list at all, to be honest - usually a method like this would be in some class which knew how to parse the XML, not an instance of the data item itself. 这是稍微奇怪的是,你会加入this在所有的名单,说实话-通常这样的方法将是一些类,知道如何解析XML,而不是数据项本身的一个实例。 It's not clear where pl is declared, but you should really consider the structure of your program. 不清楚在哪里声明了pl ,但是您应该真正考虑程序的结构。

You keep adding the same object (this) to the list. 您继续将相同的对象(此)添加到列表中。 Although you change the members, all references in the list keep referencing the same object. 尽管您更改了成员,但列表中的所有引用仍然引用同一对象。

You should create a new object and add that. 您应该创建一个新对象并添加它。

See my other post 看到我的其他帖子

Try 尝试

ProductList obj=new ProductList();
// some work on this object and then store it in List
pl.add(obj);

It should work, because it will give you the fresh object 它应该起作用,因为它将为您提供新鲜的物体

I've tried to guess the overall structure of ProductList and Product from what was posted here. 我试图从这里发布的内容猜测出ProductList和Product的总体结构。 The problem is that the list and the fields of a list element appear to be in the context of a single class, ie, ProductList. 问题在于列表元素的列表和字段似乎在单个类(即ProductList)的上下文中。 This won't do - two classes are required. 这不会做-需要两个类。

// stores the data coming from a single Element ("item") of the document
class Product {
    private String productType;
    private String hyperLinkParam;
    public setHyperLinkParam( String hlp ){
        hyperLinkParam = hlp;
    }
    public setProductType( String pt ){
        productType = pt;
    }
}

// Container for a list of products from an inventory
class ProductList {
    private ArrayList <Product> pl = new ArrayList<Product> ();
    public ProductList() {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream url = getClass().getResourceAsStream("inventory.xml");
        Document doc = db.parse(url);
        doc.getDocumentElement().normalize();

        // loop through each item
        NodeList items = doc.getElementsByTagName("item"); 
        for (int i = 0; i < items.getLength(); i++){
            Element e = (Element) items.item(i);
            // create the single product from the current item
            Product prod = new Product();
            prod.setHyperLinkParam( e.getAttribute("name").toString() );
            prod.setProductType( getTextValue( e, "productType") );
            // add it to the list
            pl.add( prod );
        }
    }

    void showList(){
        for( Product prod: pl ){
        System.out.print("getHyperLinkParam: " + prod.getHyperLinkParam());
            System.out.println("getProductType: " + prod.getProductType());
        }
    }
}

NB: Everything would be cleaner and clearer if the construction of a ProductList and of a Product would be in a Factory Class with Factory Methods makeProductList and makeProduct. 注意:如果使用工厂方法makeProductList和makeProduct将ProductList和产品的构造放在Factory类中,则一切将变得更加清晰。 A ProductList should have a method addProduct delegating the add to its pl member. 一个ProductList应该有一个addProduct方法,将add委托给它的pl成员。 And the knowledge of how to obtain a product list from the XML should be there and not in the constructor, and, similarly, the way the field values for a Product are obtained from an "item" element don't belong in the code of Product or ProductList. 而且关于如何从XML获取产品列表的知识应该存在,不是在构造函数中,并且类似地,从“ item”元素获取Product的字段值的方式也不属于产品或产品列表。

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

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