Search code examples
javaarraysobjectjgroups

Converting object array to string array


I have an item class that contains data such as itemName, price, etc and I add to it when a seller wants to sell something, like so:

public void sellItem(String itemName, double Price) throws java.rmi.RemoteException, Exception {
    items.add(new Item(itemName, price)); 

I then return all the items in the list, so a seller/buyer can browse the list.

public ArrayList<Item> listItems() {
    return items;
}

Next, I'm working on populating JGroups instances to allow for this 'Item' data to be replicated across instances. When an item has been listed, I convert to an object:

/* Create a new ItemObject containing the Items used for JGroups later */
public void createItemObject() throws Exception {
    Object[] objArray = items.toArray();
    FileOutputStream fis = new FileOutputStream("io");
    ObjectOutputStream itemObject = new ObjectOutputStream(fis);
    itemObject.writeObject(objArray);
    itemObject.close();
    fis.close();
}

Every instance of the replicated server will take this object as input and hopefully print the data within this object to its terminal window:

static Object io = new Object();
public static void getAuctionObject() throws Exception {

    FileInputStream fis = new FileInputStream("io");
    ObjectInputStream auctionObjectIn = new ObjectInputStream(fis);
    ao = auctionObjectIn.readObject();
    auctionObjectIn.close();
    System.out.println("Received object at Front End:  " + ao);
    //Print out item data.....
}

However, how would I actually iterate through this object and print out the Item data, such as 'itemName', 'price', etc?


Solution

  • Override the toString() methods on the objects so that each type returns properly-formatted strings.

    Or, if you want to maintain the original toString() method intact, create a new interface that is shared by all the object types you want to print, and that provides the same "shared method" through all those objects, with each object type specifying the interface's method's behavior.