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.
Related
First, I must say that I learned Java at school (the basics...) and C++ at university (OOP). Soon I will write a Java project, and now I'm looking for the equivalent of STL in Java.
I'm learning to use iterators in Java, I've been looking for a way to access the content of the iterator without using the methods next(), previous() (which I've seen here).
I mean the cast: iterator to Object, like operator * in pointers.
The code compiles when I write (Object)obj But I get Java.lang.ClassCastException.
The Java equivalent to STL containers are the Collection, List, Set, and Map interfaces. The most common concrete implementations of those interfaces are ArrayList, HashSet, TreeSet, HashMap, and TreeMap.
Iterators are an old, uncommonly-used interface in Java. You normally will not need to work with iterators. Instead, use enhanced for loop syntax to loop over a container directly:
List<String> names = new ArrayList<>();
for (String name: names) {
System.out.printf("Hello %s%n!", name);
}
If you do use iterators, calling next() is the way to access the container's elements. Each call returns the next element in the collection. There is no other way. An iterator is not a pointer; you can't access its contents by dereferencing it or casting it or anything like that. You call next().
This question already has answers here:
When to use LinkedList over ArrayList in Java?
(33 answers)
Closed 8 years ago.
When do I use List and when do I use ArrayList in Java? Please phrase in terms of practical situations where you would rather apply one over another. Thank you!
Edit : Also, LinkedList. Business situations where these are used, thanks, thats what's different about this question.
List is an interface. The other two are implementations of which.
You mostly want to code against interfaces. That is you wil do something like
List<String> strList = new ArrayList<String>();
Later on in the coding process, you may find that LinkedList has better performance for your scenario, so you just need to change one single place. Or maybe you don't care which concrete implementation is used, you just need "some sort of list". Then you could use an injected List implementation. Like this:
class ExampleClass{
private List<String> strList = null;
// We don't know and we don't care if Array or Linked List.
public ExampleClass( List<String> aList ){
strList = aList;
}
//...
}
For the differences between the implementations, see the links given in the comments as "possible duplicate of ..." or the JavaDoc.
***There's no difference between list implementations in both of your
examples. There's however a difference in a way you can further use
variable myList in your code.
When you define your list as:
List myList = new ArrayList(); you can only call methods and reference
members that belong to List class. If you define it as:
ArrayList myList = new ArrayList(); you'll be able to invoke ArrayList
specific methods and use ArrayList specific members in addition to
those inherited from List.
Nevertheless, when you call a method of a List class in the first
example, which was overridden in ArrayList, then method from ArrayList
will be called not the one in the List.
That's called polymorphism. You can read upon it.***
This answer was given by ATrubka here
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What are the Advantages of Enhanced for loop and Iterator in Java ?
Is there a performance difference between a for loop and a for-each loop?
Below code shows that with both for loop as well as with iterator we can iterate the elements of collection then what is the difference between for loop and iterator and why we should use only iterator in case of collection
ArrayList<String> list=new ArrayList<String>();
list.add("dipu");
list.add("alok");
list.add("alok");
list.add("jyoti");
ArrayList<Integer> al=new ArrayList<Integer>();
al.add(1);
al.add(2);
String a[]={"a","b"};
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));;
}
for(Integer t:al)
{
System.out.println(t);
}
for (Iterator iter = list.iterator(); iter.hasNext();)
{
System.out.println(iter.next());
}
Iterator it=list.iterator();
while(it.hasNext())
{
String st=it.next().toString();
System.out.println(st);
}
Though I'm not familiar with the Java Iterator, it seems very similar to .NET's IEnumerable.
The advantages of the enumerator/iterator are:
You don't have to know the size of the collection, which in some cases can require N steps to determine, increasing execution time (though it remains technically linear). Instead, you just keep moving to the next element until there aren't any.
Because the cardinality of the collection doesn't have to be known, iterators can allow collections to be generated dynamically, or "streamed" with elements being added while you begin work on what you already have. For instance, you could derive from Iterator and/or overload iterator getters to create classes that generate finite or infinite series "lazily", figuring out what each element in your enumerable collection is when you ask for it instead of when you define the collection. You could also set up a buffered stream, where you process records, packets, etc that you have received, while another thread or process works ahead of you to queue up more for you to work on.
Any collection that can provide an iterator can be traversed in exactly the same way, instead of having to know whether it's indexable, what the method or member is that defines size, etc etc etc. Iterator implementations thus provide an adapter to allow the same code to work on any collection passed to it.
Does Java have an equivalent to .NET extension methods (static methods that are not part of the class definition, but that work on instances of the type and can be called as if they were instance methods)? If so, you can define methods that take an Iterator and produce a result, which could be another Iterator. .NET's Linq library is based heavily on these, providing a very powerful collection-manipulation framework allowing for common operations to be chained together, each operating on the result of the previous operation.
Iterators are just generally safer I would say, no risk of accessing an index that isn't there. They also have a little more flexibility since you can go backwards and forwards with them whereas for loops only go one way and in many languages you cannot alter the value of the loop index within the loop (i.e. you cannot change the increment rate).
They are also the ONLY way to remove items from a collection while iterating through them. Removing an item from a collection while you were in a for loop through it would be disastrous and is generally not even allowed by Java, I forget what the exception is, but I've got one for doing that before.
Think about it, once you remove the item all the other ones shift down. Meanwhile on your next iteration your index was still incremented meaning 2 things.
First is that you will skip whatever the next element is as it was shifted to the position you just deleted from.
Second is that your loop will extend beyond the size of the collection which you have now altered.
I try to explain it with two short sentences:
With the enhanced for loop its easier to loop over it (more human readable..)
With the iterators it is possible to modify the list during the iteration, which is with the other methods not possible
The 'stream' you're iterating on might not even be indexable. That is, the iterator makes possible a very convenient 'lazy-evaluation' pattern where data isn't even loaded/constructed until the iterator asks for it. This is wonderful for repositories and database access, as well as networking.
This question already has answers here:
Does Java's foreach loop preserve order?
(2 answers)
Closed 7 years ago.
Does a java for-each loop guarantee that the elements will be presented in order if invoked on a list? In my tests it does seem to, but I can't seem to find this explicitly mentioned in any documentation
List<Integer> myList;// [1,2,3,4]
for (Integer i : myList) {
System.out.println(i.intValue());
}
#output
1,2,3,4
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method. See the documentation for the Iterable interface.
If you look at the Javadoc for List you can see that a list is an "ordered collection" and that the iterator() method returns an iterator that iterates "in proper sequence".
The foreach loop will use the iterator built into the Collection, so the order you get results in will depend whether or not the Collection maintains some kind of order to the elements.
So, if you're looping over an ArrayList, you'll get items in the order they were inserted (assuming you didn't go on to sort the ArrayList). If you're looping over a HashSet, all bets are off, since HashSets don't maintain any ordering.
If you need to guarantee an order to the elements in the Collection, define a Comparator that establishes that order and use Collections.sort(Collection<T>, Comparator<? super T>).
Yes, the Java language specs ensure that
for (Iterator<Whatever> i = c.iterator(); i.hasNext(); )
whatEver(i.next());
is equivalent to
for (Whatever x : c)
whatEver(x);
no "change in ordering" is allowed.
You could use a for loop, a la for (int i = 0; i < myList.length(); i++) if you want to do it in an ordered manner. Though, as far as I know, foreach should do it in order.