Hi,

I have initialized an array like this:

int[][] my_array= new int[28][28];
my_array[-6][12]=2;

But when i assign my_array with my_array[-6][12] it is giving me error.I know the doubt is very stupid but I am very confused.
I want to store values in an array which has negative as well as positive indexes.Is there any other way i can do it?

Dani AI

Generated

As noted, Java array indices run from 0 to length-1; a negative index is not valid and will throw an ArrayIndexOutOfBoundsException. For a clear reference on array behavior see the Java tutorial on arrays and the exception javadoc.

A simple, idiomatic solution when the logical indexes include negatives is to allocate a bounded array that covers the full logical range and translate (offset) your logical coordinates into non-negative array positions. The pattern below encapsulates that translation so callers use logical (possibly negative) coordinates:

public class OffsetGrid {
    private final int xMin, yMin;
    private final int[][] grid;
    public OffsetGrid(int xMin, int xMax, int yMin, int yMax) {
        this.xMin = xMin;
        this.yMin = yMin;
        grid = new int[xMax - xMin + 1][yMax - yMin + 1];
    }
    public void set(int x, int y, int value) {
        grid[x - xMin][y - yMin] = value;
    }
    public int get(int x, int y) {
        return grid[x - xMin][y - yMin];
    }
}

If the coordinate space is sparse or unbounded, a map is usually better. Pack two ints into one long as a map key (or use a small key class with proper equals/hashCode):

long key = (((long)x) << 32) | (y & 0xffffffffL);
Map<Long,Integer> map = new HashMap<>();
map.put(key, value);
Integer v = map.get(key);

Recommendations: follow ’s offset idea for dense, bounded grids (fast and memory-predictable); use a Map for sparse/unbounded data to save memory. For high-performance use with many primitive values, consider primitive-key/value collections (to avoid boxing). See the Java HashMap docs for map behavior and trade-offs.

Recommended Answers

All 2 Replies

no. Indices always start at 0. ALWAYS. At least thats what I have noticed.

Previous poster is absolutely correct. Absolute index of an array arr[] must be in the range [0..arr.length-1] - can't be negative, can't be equal to or greater than the length.

Notice I say "absolute index" - that's the index that the compiler sees as the value. Now, suppose you want your array to map values to points on a number line, and your number line ranges from -10 to 9, inclusive. That's 20 places, so you declare an array of 20 ints. You can then figure that what the compiler thinks is 0 corresponds to your -10, and so forth, so when you calculate the values for y at each place on the number line, you just iterate i from 0..20 and calculate the value of array using i-10 as your x value.

Easy peasy. Just make sure you keep track of when you want the index (i) and when you want the position on the number line (i-10).

I'm not sure what exactly you've got in mind, but that example might help with whatever you're trying to do.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.