gpt4 book ai didi

Java:如何创建包含数组的对象数组?

转载 作者:太空狗 更新时间:2023-10-29 16:25:28 26 4
gpt4 key购买 nike

我想创建一个名为 Product (Listproducts) 的列表对象,其中 Product 包括以下成员:

public class Product {

private Double price;
private String title;
private String description;
private List<Point>points;
...
}

Point 是另一个包含纬度和经度的对象:

public class Point{
Double lat;
Double lng;
...
}

在应用程序中,我首先必须创建列表 List products from XML file 然后在 map 上显示产品。一种产品可以位于多个位置。有谁知道创建结构(列表或链表)的最合适方法是什么,这是最容易迭代并能够链接列表的?

逻辑应按以下方式工作:1.从列表中读取每个点2.查看该点属于哪个产品3.在 map 上显示产品信息

谢谢!

最佳答案

为什么不创建一个 Map,其中键是产品,值是点列表。

Map<Product, List<Point>> productPoints = new HashMap<Product, List<Point>>();

for (Product prod: productPoints) {
for (Point point : productPoints.get(prod)) {
// construct the point and add the product info to the point
}
}

这还允许您在必要时按产品轻松过滤 map 上的点。

或者按照上面的建议使用 List 接口(interface),这样您以后可以用最少的代码更改来更改实现。

List<Product> products = new ArrayList<Product>();
for (Product prod : products) {
for (Point point : prod.getPoints()) {
// construct the point and add the product info
}
}

关于Java:如何创建包含数组的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1989364/

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