Reputation: 63
So I've been running into a few errors. When I try to add an event to a date in a month, I try to add an event into the date ArrayList
but the list doesn't have that number available. So I want to know how to instantiate a list that will have the amount of days in it.
I know you can instantiate how many months there are by using
public static List<List<String>> events = new ArrayList<List<String>>(12);
which 12 being the number of months, but is there a way to make all 12 of the arrays have 31 slots open for days?
Upvotes: 0
Views: 1569
Reputation: 4129
While @Adam's answer is probably the best way to handle this particular problem, the general question of how to initialize a multidimensional list structure should also be addressed.
The standard idiom for constructing and initializing a multi-dimensional data structure like the one you describe is to use a set of for
loops, like this:
int[][] myArray = new int[][myFirstDimension];
for(int i=0; i<a.length; i++){
int [] a = new int[mySecondDimension];
for(int j=0; j<b.length; j++){
a[j] = myInitialValue;
}
myArray[i] = a;
}
Nested ArrayList
s are constructed in a similar way to arrays, but with one important difference: The parameter passed to the ArrayList
is only an initial capacity, not the initial size. In fact, ArrayList
actually makes no guarantees about how much space it allocates, although in practice, IIRC, it typically allocates the next power of two. Attempting to index into the ArrayList
before you have initialized its contents will throw an IndexOutOfBoundsException
.
Thus, when initializing nested ArrayList
s, we typically do it like this:
List<List<String>> myList = new ArrayList<>();
for(int i=0; i<myFirstDimension; i++){
List<String> a = new ArrayList<>();
for(int i=0; i<mySecondDimension; i++){
a.add(""); // or `null`, if that is needed
}
myList.add(a);
}
Upvotes: 0
Reputation: 36703
I'd recommend completely changing your design.
Code
private class Events {
Map<Date, List<String>> events = new HashMap<Date, List<String>>();
public List<String> getEvents(int month, int day) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(0, month, date, 0, 0, 0);
Date date = calendar.getTime();
List<String> list = events.get(date);
if (list == null) {
list = new ArrayList<String>();
events.put(date, list);
}
return list;
}
}
Usage
Events events = new Events();
events.getEvents(11, 25).add("Christmas");
events.getEvents(0, 1).add("New years day");
Upvotes: 2
Reputation: 6006
Why not use
List<Map<String, Integer>> = new List<HashMap<String, Integer>>();
Upvotes: 0
Reputation: 832
I think you should change your design plan. Make a class Month with an ArrayLisy<String>(31)
which you create 12 times in another class called year or something. For myself I would do this and it makes your code more readable!
Also, when it is a fixed number of slots (and you don't want it to go over that limit), use basic arrays
Upvotes: 1