public
Created

A simple test

  • Download Gist
My2DArray.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
import java.lang.reflect.Array;
 
/**
* @author ClarenceAu
*
*/
public class My2DArray<T> {
private int m;
private int n;
private T[] entities;
@SuppressWarnings("unchecked")
public My2DArray(Class<T> type, int m, int n) {
this.m = m;
this.n = n;
this.entities = (T[]) Array.newInstance(type, m * n);
}
public My2DArray(Class<T> type, int m) {
this(type, m, m);
}
public void set(int i, int j, T value) {
this.entities[convertTo1D(i, j)] = value;
}
public T get(int i, int j) {
return this.entities[convertTo1D(i, j)];
}
public int convertTo1D(int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n)
throw new ArrayIndexOutOfBoundsException();
return i * m + j;
}
public static void main(String[] args) {
final int length = 1000;
// My2DArray<String> array = new My2DArray<String>(String.class, length);
// My2DArray<Object> array = new My2DArray<Object>(Object.class, length);
My2DArray<TestBean> array = new My2DArray<TestBean>(TestBean.class, length);
long start = System.nanoTime();
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
// array.set(i, j, i+"");
// array.set(i, j, new Object());
array.set(i, j, new TestBean());
// array.set(i, j, new String());
}
}
long elast = System.nanoTime() - start;
System.out.println("My2DArray: " + elast / 1000000000.0 + "s");
// String original[][] = new String[length][length];
// Object original[][] = new Object[length][length];
TestBean original[][] = new TestBean[length][length];
start = System.nanoTime();
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
// original[i][j] = i+"";
// original[i][j] = new Object();
original[i][j] = new TestBean();
// original[i][j] = new String();
}
}
elast = System.nanoTime() - start;
System.out.println("Original 2D Array: " + elast / 1000000000.0 + "s");
}
private static class TestBean {
 
private String name;
private int id;
 
public String getName() {
return name;
}
 
public void setName(String name) {
this.name = name;
}
 
public int getId() {
return id;
}
 
public void setId(int id) {
this.id = id;
}
 
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.