Christopher Francisco
Christopher Francisco

Reputation: 16268

Change from ArrayList to Vector

I'm working on an android game and I just noticed that since onTouchEvent runs on the UI thread, and the update/render methods are ran from a separate threads, both of them update an ArrayList which contains the entities. So obviously they conflict if they happen to modify the list at the same time.

I read that Vector class is used exactly the same as ArrayList with the only difference that Vector is synchronized, ergo they wont conflict. Is that true? if so, does it have any performance issue or something that I should be concerned about? I have never used Vector class before.

EDIT: what I actually meant was change from

ArrayList<Obj> list = new ArrayList<Obj>();

to

Vector<Obj> list = new Vector<Obj>()

But as the answers say, Vector is not recommended to use. The selected answer solved my issue.

Upvotes: 10

Views: 39904

Answers (4)

Sergio Gabari
Sergio Gabari

Reputation: 693

For those who have to fight with legacy code do just the following:

new Vector<Obj>(anyThingWhichImplemntsCollection);

Upvotes: 41

Hardcoded
Hardcoded

Reputation: 6494

As already mentioned by nachokk, synchonizedList will do the trick. synchronizedList will return a wrapper around your list, so no copying is done.
The downside is that only one call to the list can be done at a time. Two reads at the list will be sequential even if they could be done in parallel. Synchronized blocks always means a little overhead and decreaces performance if called often.

Another option would be to use a concurrent list. This means a copy in the first place, but access performance could be dramatically improved. If you have many read requests (e.g. for paintings), a CopyOnWriteArrayList will be a good choice. Reads are nearly as fast as a normal ArrayList and won't be blocked. Writes to the list will be sequential and expensive, since they have to copy the whole array.
Another good point for the CoWArrayList is that you can iterate without catching a ConcurrentModificationException. The Iterator returned by iterator() will always use the same backing array, even if the list has changed.

Upvotes: 0

ArturSkowronski
ArturSkowronski

Reputation: 1792

List<Foo> list = new Vector<Foo>(new ArrayList<Foo>());  

should work. Both of those structures implements List interface.

But like other people suggested, this is not recomended.

Upvotes: 2

nachokk
nachokk

Reputation: 14413

It's oldie Vector try to not use Vector instead use

synchronizedList

Example :

list = Collections.synchronizedList(list);

Vector is considered obsolete and deprecated read Why vector is considerer obsolete?

Upvotes: 9

Related Questions