A 2D point list holder object thing. Why? I want to post it on the wiki, as trivial as it is, with a bunch of other less trivial examples.
I also want to make sure it’s bug free. I’ve used most of the code in my own projects. I marked the methods I added that others will expect but haven’t tested myself.
import java.util.Arrays;
public class PointList
{
private int coords[];
private int size;
public PointList()
{
this(100);
}
public PointList(int capacity)
{
coords = new int[capacity * 2];
size = 0;
}
public int getX(int i)
{
return coords[0 + 2 * i];
}
public int getY(int i)
{
return coords[1 + 2 * i];
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return coords.length / 2;
}
public void add(int x, int y)
{
if(size * 2 == coords.length) { expand(); }
coords[0 + 2 * size] = x;
coords[1 + 2 * size] = y;
size++;
}
+ public void add(int index, int x, int y)
+ {
+ if(index < 0 || index > size + 2)
+ {
+ throw new IndexOutOfBoundsException();
+ }
+ if(size * 2 == coords.length) { expand(); }
+ System.arraycopy(coords, index * 2, coords, index * 2 + 2, 2 * (size - index));
+ coords[0 + 2 * index] = x;
+ coords[1 + 2 * index] = y;
+ size++;
+ }
public void clear()
{
size = 0;
}
public void setCapacity(int c)
{
if(c < size) { c = size; }
if(c < 1) { c = 1; }
coords = Arrays.copyOf(coords, c * 2);
}
protected void expand()
{
coords = Arrays.copyOf(coords, coords.length + 100);
}
+ public void ensureCapacity(int c)
+ {
+ if(coords.length * 2 < c)
+ {
+ setCapacity(c);
+ }
+ }
+ public void add(PointList other)
+ {
+ ensureCapacity(size + other.size);
+ System.arraycopy(other.coords, 0, coords, size * 2, other.size * 2);
+ }
+ public PointList copyRange(int start, int length)
+ {
+ PointList temp = new PointList(length);
+ System.arraycopy(coords, 0, temp.coords, 0, (length > size ? size : length) * 2);
+ return temp
+ }
+ public void remove(int index)
+ {
+ if(index < 0 || index > size)
+ {
+ throw new IndexOutOfBoundsException();
+ }
+ if(size > 1)
+ {
+ System.arraycopy(coords, index * 2 + 2, coords, index * 2, 2 * (size - index));
+ }
+ size--;
+ }
}
It’s surprising how frequently I exclude a remove method.