Skip to content

@OuZhencong /My2DArray.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A simple test
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.