ArrayList vs Vector [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the differences between ArrayList and Vector?
I've been using Vectors quite a lot in my recent program. However I've read somewhere that Vectors are a bit old. Whether that means it will be obsolete or phased out of Java is debatable. So the recommendation was that ArrayLists should be used instead. I've noticed that ArrayLists don't have a method remove(int index, Object object) while vectors do. The reason I ask is suppose I add a string, say "String 1". And I attempt to add the same string again. How do I remove the first string without counting the occurrences of it in an array list.

However I've read somewhere that Vectors are a bit old : Yes vector class is considerd as legecy and is still in library to support old applications. It is replaced by Collections.synchronizedList(list) .
I've noticed that ArrayLists don't have a method remove : You can remove the data based on Index. if u want to remove the object use boolean java.util.ArrayList.remove(Object o) : dont forget to override the equals and hashcode method :)
How do I remove the first string without counting the occurrences of it in an array list : Best thing is to use set. If thread safty is a concern use <Object> Set<Object> java.util.Collections.synchronizedSet(Set<Object> s)
Hope all your questions are clarified.
Regards,
Punith

Related

Is there a way to remove a custom Object from every occurrence? [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 3 years ago.
I'm trying to remove every GameObject which meet certain criteria (health<0), completely from every occurrence, so every ArrayList it might be in, and such.
I have a main ArrayList containing every GameObject that may get removed, and I'm trying to iterate through that ArrayList with a For-Each, checking each element for the criteria, and removing it.
This however results in ConcurrentModificationException, which I know the reason to, but do not know how to work around it. Any help would be much appreciated!
As #JacobG. mentioned in his comment, perhaps the "best" way to do this (where "best" is going to be a matter of personal preference) is via the .removeIf() method. Here's an example (which assumes a getHealth() method on your objects):
List<GameObject> gameObjects = new ArrayList<>();
// Some code here to populate the list
gameObjects.removeIf(x -> x.getHealth() < 0);
if you have all the items to be removed in a separate ArrayList, you could use CollectionUtils.subtract() method from apache-commons-collections to remove them from other lists :
yourList = (ArrayList<GameObject>)CollectionUtils.subtract(yourList, listWithObjectsToRemove);
See this link

List insertion efficency [duplicate]

This question already has answers here:
When to use LinkedList over ArrayList in Java?
(33 answers)
Closed 7 years ago.
I have to sort a large list (more than 10,000 elements). On adding an element I have to insert it on the right place. I saw that an ArrayList will shift all the element that are after the insertion point.
How do all the different implementation of the List interface behave in such a case? And what are the pros and the cons when choosing one implementation over the other?
The two main implementations of List are ArrayList and LinkedList. There are others but they are generally used in specialis situations.
ArrayList can be accessed very quickly by index because it is backed by an array - you just need array[i] - but modifying the list requires moving much of the underlying array around so that is not efficient.
You can add/remove items with LinkedList very efficiently but finding the nth entry is slow because it has to start at the head and walk the list counting nodes until it gets to the required location.
Probably duplicate, but i will give you a hint.
To sort your data you can use:
Collections.sort(List list);
method, it will convert List to Array anyway, so you don't have to care about too much about type of List implementation. All it needs is interface Comparable implemented in your objects.
Can your data contain duplicates?
If NO, you can use a TreeSet<?>
If YES, you can use a TreeMap<?, Integer> where the Integer is the count per item

ArrayList vs LinkedList Java [duplicate]

This question already has answers here:
When to use LinkedList over ArrayList in Java?
(33 answers)
Closed 8 years ago.
What is the difference between ArrayList and LinkedList? I watched a video on it by TheNewBoston but i am still confused. Please answer in a short form and in plain English. Please do not use any advanced code.
ArrayList is a list implementation that's backed by an Object[]. It supports random access and dynamic resizing.
LinkedList is a list implementation that uses references to head and tail to navigate it. It has no random access capabilities, but it too supports dynamic resizing.
Bear in mind that both support the get(int index) signature, but the difference between the two implementations is performance: with an ArrayList, that's a matter of going to the index position, whereas with a LinkedList, you have to walk down the object chain (either from the front or the rear, depending on what you've indexed into).
For an arrayList, you have access to every element, which has its own index value. For example, if you want the third item in an ArrayList, you just have to perform arrList.get(2) to get this value. An ArrayList is made using a similar structure as an array.
For a linked list, you ONLY have access to the first element, but each element has access to the next one. So, to get to the third element, you have to go to the first, then second, then finally third. Think of a LinkedList like a chain. If you have the first part of the chain but cut off its access to the second part, you lose the rest of it too.
They both have their advantages and disadvantages, in terms of memory, processing time, and ease of use. Let me know if you have any more specific questions or want clarification.

When would you use a java.util.LinkedList [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to use LinkedList<> over ArrayList<>?
This is a genuine attempt to know when would one use a LinkedList;
From what i understand since the java.util.LinkedList doesn't support random access, the only way to get the nth element is to skip from 1 to (n-1) or use get(n) which itself is very inefficient.
So why would one use a LinkedList? An ArrayList would serve for most part unless you want to iterate the collection from both sides using a ListIterator?
Think about this method:
List list = // choose your list here
list.add(0, new Object());
For large lists, LinkedList will heavily out-perform ArrayList. The same applies for
list.remove(0);
... and many other methods. For more information, I suggest reading about the java.util.Deque interface, which is also implemented by LinkedList
Consider 3 common operators on these sorts of data structures: random element access, adding elements, and removing elements.
In LinkedList, your random element access is slow (O(N)), but adding and deleting are fast (O(1). For ArrayList, the reverse is true: random element access is fast (O(N)), but adding and removing elements are slower.
You need to look at which operations your system will do more of and use the appropriate data structure.
LinkedList better suited (as compared to ArrayList) for insertions/deletion for arbitrary indexes. When inserting or deleting from an ArrayList, the internal array has to be shifted. For LinkedList, it's a matter of simply repointing the the nodes' pointers.

How to initialize a dynamic array in java?

If I have a class that needs to return an array of strings of variable dimension (and that dimension could only be determined upon running some method of the class), how do I declare the dynamic array in my class' constructor?
If the question wasn't clear enough,
in php we could simply declare an array of strings as $my_string_array = array();
and add elements to it by $my_string_array[] = "New value";
What is the above code equivalent then in java?
You will want to look into the java.util package, specifically the ArrayList class. It has methods such as .add() .remove() .indexof() .contains() .toArray(), and more.
Plain java arrays (ie String[] strings) cannot be resized dynamically; when you're out of room but you still want to add elements to your array, you need to create a bigger one and copy the existing array into its first n positions.
Fortunately, there are java.util.List implementations that do this work for you. Both java.util.ArrayList and java.util.Vector are implemented using arrays.
But then, do you really care if the strings happen to be stored internally in an array, or do you just need a collection that will let you keep adding items without worrying about running out of room? If the latter, then you can pick any of the several general purpose List implementations out there. Most of the time the choices are:
ArrayList - basic array based implementation, not synchronized
Vector - synchronized, array based implementation
LinkedList - Doubly linked list implementation, faster for inserting items in the middle of a list
Do you expect your list to have duplicate items? If duplicate items should never exist for your use case, then you should prefer a java.util.Set. Sets are guaranteed to not contain duplicate items. A good general-purpose set implementation is java.util.HashSet.
Answer to follow-up question
To access strings using an index similar to $my_string_array["property"], you need to put them in a Map<String, String>, also in the java.util package. A good general-purpose map implementation is HashMap.
Once you've created your map,
Use map.put("key", "string") to add strings
Use map.get("key") to access a string by its key.
Note that java.util.Map cannot contain duplicate keys. If you call put consecutively with the same key, only the value set in the latest call will remain, the earlier ones will be lost. But I'd guess this is also the behavior for PHP associative arrays, so it shouldn't be a surprise.
Create a List instead.
List<String> l = new LinkedList<String>();
l.add("foo");
l.add("bar");
No dynamic array in java, length of array is fixed.
Similar structure is ArrayList, a real array is implemented underlying it.
See the name ArrayList :)

Categories