简体   繁体   中英

Storing a reference to the object in ArrayList

Hey everyone i am trying to store the current reference to an arraylist "pl". eg 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

    @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

    <%
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. The value of this is just a reference to the "current" object - and you're modifying the contents of that object in the loop.

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. It's not clear where pl is declared, but you should really consider the structure of your program.

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. 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. 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. A ProductList should have a method addProduct delegating the add to its pl member. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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