On many occasions, I need to store data of different data-types where they easily correspond to each other. I see many people with this issue, and here is one of the answers. Parallel arrays. It may seem too easy but if it works, it works. Let me start by telling you a story....
Steve was hired by a dog show to record the results. In this he had to store the dogs' names, and their corresponding three test scores. Unfortunately, the dog show did not know at the time how many dogs were participating but, he had to develop a system that could easily store the data.
Well, Steve developed a class that represented the dog show, and it was quite easy to implement.
He started by designing the basic class structure and importing the proper libraries.
import java.util.ArrayList;
public class DogShow {
}
But now he needs to make 4 corresponding arrays to meet all of his requirements.
private ArrayList<String> names = new ArrayList<String>(); private ArrayList<Integer> score1 = new ArrayList<Integer>(); private ArrayList<Integer> score2 = new ArrayList<Integer>(); private ArrayList<Integer> score3 = new ArrayList<Integer>();
This now allowed him to add the information synchronously. Now he needed to add the methods that add and print out the dogs.
public void addDog(String name, int s1, int s2, int s3) {
names.add(name);
score1.add(s1);
score2.add(s2);
score3.add(s3);
}
public void printDogs() {
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i) + ":");
System.out.println("\t" + score1.get(i) +
"\t" + score2.get(i) +
"\t" + score3.get(i));
System.out.println();
}
}
This makes all of dogs number 1's attributes be in position 1 of all 4 arrays so it is easy to print out.
Now, all Steve has to do is develop an interface by which he adds the dogs, but for now, he will test it it with this tester class.
public class Main {
public static void main(String[] args) {
DogShow ds = new DogShow();
ds.addDog("Sparky", 1, 1, 1);
ds.addDog("Patches", 2, 2, 1);
ds.printDogs();
}
}
Alright! I hope I adequately described how to use parallel arrays to store data.
Cheers!









MultiQuote




|