I'm trying to create a lazy loading method using Java Lists that takes in an index, adds elements to the List until the index is valid, and returns the value at that index.
For example, say I have a List like this [0, 1, 2, 3]
. If I call my method with it and pass in index 1, it should return 1 without changing the List in any way. If I call my method with it and pass in index 5, it should return 0 (the default Integer value) and my List should now look like this [0, 1, 2, 3, 0, 0]
.
It seems pretty simple to implement at first, but I run into problems when I try to pass in Lists like a List<List<String>>
. I know that you can't instantiate a list, so I try to make an ArrayList, but it doesn't work.
Here's the current incarnation of my method
protected <T> T getOrCreateAt(int index, List<T> list, Class<T> elementClass) {
while (list.size() < index + 1) {
try {
list.add(elementClass.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
System.exit(1);
} catch (IllegalAccessException e) {
e.printStackTrace();
System.exit(1);
}
}
return list.get(index);
}
Here's one place where I call it
List<List<String>> solutionText = new ArrayList<List<String>>();
for (Node node : solution) {
List<String> row = getOrCreateAt(node.rowNo, solutionText, ArrayList.class);
getOrCreateAt(node.colNo, row, String.class);
row.set(node.colNo, String.valueOf(node.cellNo));
}
The second call to getOrCreateAt works, but the first one doesn't compile.
How do I get my lazy loading method to work on interfaces and abstract classes?