我对如何选择数据结构感到困惑。假设我有以下数据-产品、价格、公司、总可用数据。我从分局得到的。现在,我想用excel或csv来表示这一点,与我从db公司wise获得的顺序相同。所以我选择了下面的数据结构。
Map<String, TreeMap<Integer, TreeMap<String, String>>> .第一个字符串表示Company Integer在db中的记录位置,这样我就可以按相同的顺序显示。TreeMap包含其他值。
我能为这个需求选择更好的数据结构吗?
发布于 2014-10-07 14:18:22
是的,完全正确。
更好的解决方案是面向对象的:
public class Product {
private String name;
private String company;
private Money total;
private boolean available;
// Add necessary methods.
}数据结构将是一个List<Product>。
你的方式太原始了。
发布于 2014-10-07 14:20:50
传统的数据结构遵循结构化编程模式。面向对象编程起源于结构化编程,但又增加了行为局部性的概念。简而言之,数据不仅是集中的,而且与数据相匹配的行为(方法)也是集中的。
这允许数据隐藏(对于维护非常有用,因为正确的数据格式往往会随着时间的推移而改变),并为其他更高级的行为打开了大门(polymorphisim是可能的,因为行为是本地化的)。然而,它对纯play数据结构方法没有多大作用。最接近旧学校数据结构的是表示它们的对象。
当选择一个数据结构时,如果你真的不知道什么是重要的,你真的没有条件让你选择一个数据结构而不是另一个数据结构。当然,您可以一直使用HashMap和HashSet,这在很多情况下都很好;但是,有一些琐碎的例子表明,这些选择可能是最糟糕的选择。简而言之,您需要知道访问模式才能做出正确的选择。
发布于 2014-10-08 15:14:03
正如duffymo建议的那样,您应该考虑一种面向对象的方法。考虑使用如下示例:
import java.util.ArrayList;
public class Product {
private String name;
private double price;
private String company;
private int total;
private boolean available;
public Product(String name, double price, String company, int total,
boolean available) {
super();
this.name = name;
this.price = price;
this.company = company;
this.total = total;
this.available = available;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + ", company="
+ company + ", total=" + total + ", available=" + available
+ "]";
}
public static void main(String[] args) {
ArrayList<Product> products = new ArrayList<Product>();
Product product1 = new Product("PlayStation 4", 300, "Sony", 10, true);
Product product2 = new Product("XBOX One", 400, "Microsoft", 0, false);
Product product3 = new Product("WiiU", 250, "Nintendo", 5, true);
products.add(product1);
products.add(product2);
products.add(product3);
System.out.println("-- Products --");
for (Product product : products) {
System.out.println(product.toString());
}
}
}它将产生以下产出:
-- Products --
Product [name=PlayStation 4, price=300.0, company=Sony, total=10, available=true]
Product [name=XBOX One, price=400.0, company=Microsoft, total=0, available=false]
Product [name=WiiU, price=250.0, company=Nintendo, total=5, available=true]如您所见,您将能够轻松地管理您的项目列表。
希望能帮上忙。
克莱门西奥·莫拉莱斯·卢卡斯
https://stackoverflow.com/questions/26238077
复制相似问题