gpt4 book ai didi

java - 将对象数组转换为字符串数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:40 26 4
gpt4 key购买 nike

我有一个项目类,其中包含项目名称、价格等数据,当卖家想要出售某物时,我会添加到其中,如下所示:

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

然后我返回列表中的所有项目,以便卖家/买家可以浏览列表。

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

接下来,我将致力于填充 JGroups 实例,以允许跨实例复制此“项目”数据。列出项目后,我将转换为对象:

/* 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();
}

复制服务器的每个实例都将此对象作为输入,并希望将此对象中的数据打印到其终端窗口:

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.....
}

但是,我如何实际遍历此对象并打印出项目数据,例如“itemName”、“price”等?

最佳答案

覆盖对象上的 toString() 方法,以便每种类型都返回格式正确的字符串。

或者,如果你想保持原来的toString()方法完好无损,创建一个新的interface,它被你想要打印的所有对象类型共享,并且通过所有这些对象提供相同的“共享方法”,每个对象类型指定接口(interface)方法的行为。

关于java - 将对象数组转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34074142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com