开发者

Java: How to create an array of objects which include arrays?

I would like to create a list objects called Product (Listproducts) where Product includes the following members:

public class Product {

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

Point is another object which includes开发者_如何学Python latitude and longitude:

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

In the application I first have to create the list List products from XML file and then display the products on the map. One product can be located at several locations. Does anyone know what is the most appropriate way to create the structure (a list or linked list) which is the easiest to iterate through and enables to link the lists?

The logic should work the following way: 1. Read each point from the list 2. Check which product belongs to the point 3. Display the product informations on the map

Thank you!


Why not create a Map where the keys is the product and the value is the list of Points.

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

This also allows you to easily filter the points on the map by product if necessary.

Or use the List interface as suggested above so you can later change the implementation with minimal code changes.

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


An ArrayList of Product should suffice.

But your algorithm better be Product-centric, not Point-centric.

  1. iterate over all products
  2. iterate over all the points in the current product
  3. add the product info to the point


Any class that implements Iterable, which returns an Iterator from the Collections Framework, can be conveniently iterated using the for-each syntax, introduced in Java 1.5. Your top-level collection would be

List<Product> products = new ArrayList<Product>();

An you could iterate it like so:

for (Product p : products) { ... }

By using the interface type, List, you can later change to another List implementation as required.


Either of these is perfectly okay:

List<Product> products = new ArrayList<Product>();

or

int numProducts = DEFAULT_VALUE; // Have to know this in advance.
Product [] products = new Product[numProducts];

What you're really asking here is "How do I bind XML to Java objects?"

Have a look at the javax.xml.bind Marshaller and Unmarshaller interfaces.


If I understand you correctly, you need to be able to find all Points given a Product, and vice-versa? I think you should add a List to Point in that case. I would use a LinkedList if you are just going to be iterating through them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜