I am new to Java, I want to store an array of pair of doubles. My code looks like this:
import java.util.ArrayList;
import java.util.Map.Entry;
List
Another approach, and probably the most efficient way to store and array of double pairs is to use a single array of doubles, and use (2*i) and (2*i + 1) as your indexing scheme. Additionally you gain the advantage that the array will be initialized to all 0s when you create it, no additional steps required. Unfortunately there is a little extra coding overhead to implement add() and remove(), but surprisingly, it's probably less than creating your own container class for the pair.
class MyClass {
double[] values;
int count;
MyClass(int initialCapacity) {
values = new double[initialCapacity*2];
}
// adding a pair
void addPair(double x, double y) {
if (count*2 >= values.length) {
values = Arrays.copyOf(values, values.length*2);
}
values[count*2] = x;
values[count*2 + 1] = y;
count++;
}
void remove(int index) {
if (index >= count) throw new IndexOutOfBoundsException();
if (index < --count) {
System.arraycopy(values, (index+1)*2, values, index*2, (count - index) * 2);
}
}
int size() { return count; }
// both these should check that index < count.
double getX(int index) { return values[index*2]; }
double getY(int index) { return values[index*2 + 1]; }
void exampleIteration() {
// getX/Y accessors are examples of how to get
// the values, but it will be more efficient
// in most cases to just access the array
// array directly as so...
for (int i=0 ; i