0

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];
2
  • yeah, sorry should have specified Commented Dec 1, 2013 at 0:27
  • New to the site, sorry Commented Dec 1, 2013 at 3:07

2 Answers 2

3

The directly equivalent operations between Java arrays and lists are:

  • list.get(i) is equivalent to the expression array[i]
  • list.set(i, v) is equivalent to the statement array[i] = v;
  • list.size() is equivalent to the expression array.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.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, the code i am writing is for a priority queue for Dijkstra's Alogrithm. I think I'm kinda pinned into using arrayList.
2
ArrayList heapList = new ArrayList(Arrays.asList(heap));
heapList.set(hole, heapList.get(child));

heapList.set(hole, temp);

heapList.set(hole, heapList.get(hole/2);

2 Comments

Ahhh, thank you. I figured there had to be a better way then using a bunch of variables and swapping things in and out.
@user3003584 - Why would you expect that? That's how you would do it with an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.