存储一个字符串和两个双打java

我编写了一个程序,它给了我三个数组。一个字符串数组和两个dole数组….但我想将它们保存在一个东西中(我不知道它是否是一个数组或矩阵)…. 。

例如:我有一个要读取的文件,输入类似于:

Apple 2.3 4.5 Orange 3.0 2.1 Pear 2.9 9.6 etc...... 

我已经制作了三个数组,一个存储字符串的名称,另外两个存储双列的两列……

但是我想将整行“(苹果2.3 4.5)”存储在一件事中,这样如果我想找到苹果我也得到苹果的相关价值…..你能不能请各位给我一个提示我怎么办?那? 我想过有三个缩小数组,但我无法弄清楚如何初始化,因为它将有一个字符串值和两个双精度……

我不知道该怎么做….任何帮助都将受到高度赞赏….提前谢谢。

一个很好的通用解决方

 public class Triple { private final L first; private final K second; private final V third; public Triple(L first, K second, V third) { this.first = first; this.second = second; this.third = third; } public L getFirst() { return this.first; } public K getSecond() { return this.second; } public V getThird() { return this.third; } } 

哪个可以这样实现:

 Triple myTriple = new Triple<>("Hello world", 42, 666); 

但这里的真实概念是将数据点表示为代码中的对象 。 如果你有一组数据(“我有一个字符串和两个含义的东西 ”),那么你可能希望将它封装在一个类下。

 class Triple { private String name; private double d1; private double d2; public Triple(String name, double d1, double d2) { this.name = name; this.d1 = d1; this.d2 = d2; } } 

那你可以做

 Triple[] fruits = new Triple[3]; fruits[0] = new Triple("Apple", 42.0, 13.37); 

我真的建议你阅读一本关于面向对象编程的好教程,比如我最喜欢的 ,特别是第25章以上。

 public static void main(String[] args) throws Exception { Map> theMap = new HashMap>(); String [] fruits = {"Apple","Pear","Lemon"}; Double [] firstDArray = {1.1,2.2,3.3}; Double [] secondDArray = {11.11,22.22,33.33}; for(int i = 0; i < fruits.length; i++){ List innerList = new ArrayList(); innerList.add(firstDArray[i]); innerList.add(secondDArray[i]); theMap.put(fruits[i], innerList); } for(Entry> en : theMap.entrySet()){ System.out.print(en.getKey() + " : "); for(Double d : en.getValue()){ System.out.print(d + " "); } System.out.println(); } } 

在我的示例中,我使用对应于数字列表(双精度)的地图。 映射的关键字(字符串)是第一个数组中的字符串,列表包含与每个其他数组的字符串对应的数字。 上面的例子给了我输出:

 Pear : 2.2 22.22 Lemon : 3.3 33.33 Apple : 1.1 11.11