I'm trying to become more acquainted with ArrayList. I was wondering how to do the equivalent operations with an Array List as compared to tan array.
heap[hole]=heap[child];
heap[hole]=temp;
heap[hole]=heap[hole/2];
-
yeah, sorry should have specifiedCSnewb– CSnewb2013年12月01日 00:27:19 +00:00Commented Dec 1, 2013 at 0:27
-
New to the site, sorryCSnewb– CSnewb2013年12月01日 03:07:24 +00:00Commented Dec 1, 2013 at 3:07
2 Answers 2
The directly equivalent operations between Java arrays and lists are:
list.get(i)is equivalent to the expressionarray[i]list.set(i, v)is equivalent to the statementarray[i] = v;list.size()is equivalent to the expressionarray.length
There is also an equivalence between the "for each" iteration of arrays and lists.
These equivalences apply for all kinds of List ... not just ArrayList. However for some List implementations, the positional set and get methods are expensive.
Having said that, wrapping an array as a list (using Arrays.asList) is something you would only do if you needed to generalize over arrays and lists. And it won't work for arrays of primitive types. If what your is an array, and your algorithm calls for an array (i.e. it requires no higher level list operations like insertion, removal, etc), it is best to stay clear of the List API.
1 Comment
ArrayList heapList = new ArrayList(Arrays.asList(heap));
heapList.set(hole, heapList.get(child));
heapList.set(hole, temp);
heapList.set(hole, heapList.get(hole/2);