java - ArrayList with unlimited predefined values -
i know how initialize arraylist has unlimited amount of predefined values, access element of arbitrary index , update value.
for example, arraylist testarraylist
initiated int
value 0
, use testarraylist.set(123, 15)
set 124th element in arraylist 15
instead of getting out of bound exception. when queries testarraylist.get(99999)
, predefined value 0
.
i've been trying initialize arraylist first use loop add 0
s it, have decide how big initial arraylist should be. if made arraylist add 100 0
s it, couldn't .get(200)
on before adding amount of 0
s.
is i'm looking possible arraylist? if not, recommend alternative solutions?
thank you.
edit: reason wanted list wanted able iterate through in order. i'm making simple calendar-like program, add/retrieve/modify "notes" of arbitrary "date", able print out notes of every "day" given specific period.
you don't want create arraylist
, since in order populate 99999
'th index, you'll have populate indices 0
99998
first, wasteful.
a hashmap<integer,integer>
better option, since populate indices care about.
a hashmap
integer
key can thought of if mapping indices of "sparse arraylist" small array, reduces storage requirements while keeping expected insertion , lookup times constant.
for example:
map<integer,integer> map = new hashmap<>(); int value = map.getordefault(99999,0); // return 0 if map has no value // key 99999 map.put (99999, value + 1);
edit: seeing requirement iteration order, can use treemap<integer,integer>
instead of hashmap<integer,integer>
. way iterating on keys according numeric order.
Comments
Post a Comment