This question already has answers here:
Java vector capacity finding the vector size
(2 answers)
Closed 8 years ago.
I have this code.
import java.util.Vector;
import java.util.Enumeration;
/*Part Of My Private Code*/
private Vector clietns = new Vector();
private DataOutputStream remoteOut;
/*Part Of My Private Code*/
clients.addElement(remoteOut);
/*Part Of My Private Code*/
Enumeration e = clients.elements();
System.out.println(e + "");
This returns the hex code of Enumeration e.
How could I obtain the exact number of elements (in integer).
With the method size() from Vector. Enumeration doesn't give you that method, since it can be used to enumerate elements even if the full number isn't known.
Next time you're wondering a thing like this, please go see the Javadocs first.
As a last tip, Vector and Enumeration are considered outdated. You should use ArrayList and Iterator instead.
Use the Vector.size method. It will tell you the number of elements in the vector.
I think you cannot get the number of items from an Enumeration.
Note that the only two methods of this interface are:
hasMoreElements()
E nextElement()
So it is not intended to behave as a collection that usually knows the number of items inside them.
You should use vector size() method instead that returns an integer.
Questions like this are best to do a little research before posting.
Take a look at the API page for Java and you'll find what you're looking for. (Hint, the function is going to return an int)
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
Related
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
This question already has answers here:
Difference between Java Enumeration and Iterator
(10 answers)
Closed 6 years ago.
I'm a newbie in java,
I want to traverse the elements in a Vector. I'm getting the same result when I use Iterator / Enumeration interfaces.
As Vector is slow because it is synchronized. Does it enhance the performance in any aspect if I use Iterator / Enumeration.
Here's what I've tried
import java.util.*;
class vectorClass{
public static void main(String args[]){
Vector<String> vector = new Vector<String>();
vector.add("This is a vector Example\n");
vector.add("This is a next line!");
Enumeration en = vector.elements();
while(en.hasMoreElements()){
System.out.print(en.nextElement());
}
System.out.println();
Iterator en1 = vector.iterator();
while(en1.hasNext()){
System.out.print(en1.next());
}
}
}
O/P:
This is a vector Example
This is a next line!
This is a vector Example
This is a next line!
There are no performance differences between Enumeration or Iterator. However, I would foster the use of Iterator since Enumeration is now deprecated (from the doc):
NOTE: The functionality of this interface is duplicated by the
Iterator interface. In addition, Iterator adds an optional remove
operation, and has shorter method names. New implementations should
consider using Iterator in preference to Enumeration.
By the way, if you are not forced to use Vector, use ArrayList instead since Vector is slower because of constant synchronization but still not thread-safe. See this answer for details.
From the javadoc, it is also recommended to use ArrayList instead of Vector:
Unlike the new collection implementations, Vector is synchronized. If
a thread-safe implementation is not needed, it is recommended to use
ArrayList in place of Vector.
This question already has answers here:
Java class vs array memory size?
(3 answers)
Closed 8 years ago.
Which is more efficient, take less memory, faster to loop through and why?
case 1 :
ArrayList<int [9]>
case 2:
int [9][9]
Thank you
[Assuming you meant ArrayList<> rather than Array<>, since the latter is impossible].
By all technical measures, a native array will always be faster and smaller than an ArrayList<>, although the difference may in many cases be very minimal. Internally an ArrayList uses a native array to store its elements, so it cannot possibly outperform that array.
However the ArrayList<E> has the advantage that it implements all of the List<E> interface as well as Collection<E> and Iterable<E>. This can make your code far simpler by allowing you to directly pass the object to any function that will accept parameters that implement those interfaces.
A further advantage of ArrayList<E> is that the array can transparently grow in size so it may be preferred if you do not know in advance how large the array has to be. However that itself comes at a performance cost - if the new size is larger than the current capacity of the backing store array then a whole new array must be created, and then the original elements all copied into it - an O(n) operation.
I think you meant ArrayList?
if thats is what you meant: then an array (int[][]) is always faster than the list ArrayList<Integer[]>
Because ArrayList uses an array, and everytime you remove a value, it rewrites the whole array.
Conclusion: unless you are going to consistently remove/add values NOT to the end of your "array", use a regular array (int[][]), but if you will, use ArrayList<int[]>
Array of int[] and int[][] are the same thing, called by different names. Considering that only one declaration is valid in java (the int[][]), whats the question?
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.
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