I have written a program which gives me three arrays.A string array and two dole arrays.... But I want to save them in one thing(I don\'t know if it would be an array or matrix)
A nice generic solution:
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;
}
}
Which can be implemented as such:
Triple<String, Integer, Integer> myTriple = new Triple<>("Hello world", 42, 666);
But the real concept here is representing a point of data as an object in your code. If you have a set of data ("I have a string and two ints that mean something"), then you would want to encapsulate it under a single class.
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();
}
}
In my example, I use a map corresponding to a list of numbers (doubles). The key to the map (string) is the string from the first array, and the list contains the numbers corresponding to the string from each other array. The above example gave me the output:
Pear : 2.2 22.22
Lemon : 3.3 33.33
Apple : 1.1 11.11
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;
}
}
Then you can do
Triple[] fruits = new Triple[3];
fruits[0] = new Triple("Apple", 42.0, 13.37);
I really suggest you to read a good tutorial on Object Oriented Programming, like my favorite, especially Chapter 25+.