我编写了一个程序,它给了我三个数组。一个字符串数组和两个dole数组.... 但是我想把它们保存在一件事上(我不知道它是不是阵列或矩阵)......
Forexample: 我有一个要读取的文件,输入类似于:
Apple 2.3 4.5
Orange 3.0 2.1
Pear 2.9 9.6
etc......
我已经制作了三个数组,一个存储了字符串的名称,另外两个存储了双列的两列......
但我想存储整行"(苹果2.3 4.5)"在一件事情,所以如果我想找到苹果我也得到相关的苹果价值..... 你能不能请各位给我一个提示我该怎么做? 我想过有三个缩小数组,但我无法弄清楚如何初始化,因为它将有一个字符串值和两个双倍......
我不知道该怎么办...... 任何帮助将非常感谢.... 提前谢谢。
答案 0 :(得分:3)
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);
我真的建议你阅读一篇关于面向对象编程的好教程,比如my favorite,尤其是第25章+。
答案 1 :(得分:3)
一个很好的通用解决方案:
public class Triple<L, K, V> {
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<String, Integer, Integer> myTriple = new Triple<>("Hello world", 42, 666);
但这里的真实概念是在代码中将数据点表示为对象。如果你有一组数据(“我有一个字符串和两个int表示某些东西”),那么你可能希望将它封装在一个类中。
答案 2 :(得分:-3)
public static void main(String[] args) throws Exception {
Map<String,List<Double>> theMap = new HashMap<String,List<Double>>();
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<Double> innerList = new ArrayList<Double>();
innerList.add(firstDArray[i]);
innerList.add(secondDArray[i]);
theMap.put(fruits[i], innerList);
}
for(Entry<String,List<Double>> 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