This question already has answers here:
Collections.emptyList() vs. new instance
(7 answers)
Closed 3 years ago.
I found emptyEnumeration(), emptyIterator(), emptyList() and other methods in Collections class. I searched for examples and purpose but could not found an appropriate one.
It would be a great help if someone can explain with project usability example, wehre emptyList() needs to be created and it is also better to go with it than going with creating a new ArrayList<>() without adding any elements.
They actually return a casted, single instance, so you don't create new objects on the heap for each call to emptyList(). So it's faster and saves memory and GC.
It's an initializer that is used internally by List implementations to decide whether they actually need to allocate space (even adding elements) or keep the list untouched if no elements will be added at runtime (because it happens sometimes, more often than you may think).
Those objects are immutable so you can safely reuse the same instance anywhere, without the synchronization you usually put in place to ensure object status integrity.
The purpose of the empty collection is to be an empty collection! As remarked in a comment, there are times when it is appropriate for a method that returns a collection to be returning an empty collection.
As for why (e.g.) Collections.emptyList() is useful: well, why create your own empty list when you can reuse an existing empty list? It's a minor convenience, a minor saving on memory.
If your code naturally arrives at a point where it (a) knows it needs to return an empty collection, and (b) does not have an empty collection that was created 'naturally', by which I mean something like having created the collection to hold results and then failed to find any such results, then the Collections facilities are handy.
Related
I want to convert a set to a list. Which method should I prefer (I dont care if it's immutable or not):
version 1:
return List.of(myHashSet().toArray());
or version 2:
return new ArrayList<Strategy>(myHashSet());
Are there any other differences besides that version 1 is immutable? For example, List.of is more space efficient in compare to ArrayList.
The only differences I see between your 1 and 2 are:
List.of produces a shallowly immutable list. You cannot add or remove items from the list. Of course, the state within each object contained in the list would still be mutable if already so. Your # 1 results in an immutable list while the ArrayList of # 2 is mutable.
With # 2, you know and control the concrete class of the resulting List. With # 1, you neither know nor control the concrete class used behind the scenes when calling List.of. The List.of feature is free to use any class that implements List interface, possibly even a class not publicly available with the Java Collections Framework. The List.of feature might even be smart about choosing an optimized class appropriate to your particular collected objects.
You said:
List.of is more space efficient in compare to ArrayList.
You cannot make that claim, if you mean usage of memory (RAM). As discussed above, you neither know nor control the choice of class used to implement List interface when calling List.of. The class used might vary depending on your data, and might vary by version of Java used at runtime.
As for memory used by the call to toArray, an array of objects is really just an array of references (pointers). Creating that array takes little memory and is fast. Object references are likely to be a value of four or eight octets (depending on your JVM being 32-bit or 64-bit), though not specified by Java. In creating the array, it is not as if the content of your element objects are being duplicated. So for most common apps the brief creation and disposal of that array would be insignificant.
And, as commented by Kuhn, Java 10 saw the arrival of a new factory method List.copyOf that takes a Collection. So no need to call toArray.
List<Strategy> myStrategyList = List.copyOf( myStrategySet ) ;
Conclusion:
If you need an immutable list, use List.copyOf.
If your need mutability or any other feature specific to a particular
implementation of List, use that particular class.
This question already has an answer here:
How to give java enough time to assign a value to a variable? [closed]
(1 answer)
Closed 7 years ago.
I have a HashSet<User> and a User declared outside a while loop, and inside the loop I am setting the name with a setter method and then adding the User to the HashSet with add(User).
This seemed to only update the single User in the HashSet. Only when I declare the User within the while loop is a new User added every time to the HashSet.
I am thinking this is because if the HashSet add() method receives an object with the same memory address as an object currently in the set, it will only update the object and not add another new object to the HashSet. Is this correct?
Then instantiating the User within the loop will cause it to have a different memory address and thus be added to the HashSet as a new object.
I can put code on here, but this is for an assignment and I don't think my professor would like me to share code. The question I have is more about the Java language and not about my assignment, as you can see. If everyone absolutely needs to see code, however, I'll post something useful.
I am thinking this is because if the HashSet add() method receives an object with the same memory address as an object currently in the set, it will only update the object and not add another new object to the HashSet. Is this correct?
That is correct. A HashSet by definition will allow for only one of each unique object. However, the part about updating the object is irrelevant to its membership in the HashSet. Since the HashSet contains only references, any changes you make to the objects (in or out of your while loop) will reflect in the HashSet automatically.
Then instantiating the User within the loop will cause it to have a different memory address
Also true. You'll have different references per object for each instantiation. The HashSet will store one and only one of each.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a List vs. an ArrayList?
Ive used both of them, but im just wondering what are the pros and cons between them? What are the major differences? And which one is better to use?
Thanks.
List is an interface implemented by ArrayList class. Another well-known implementation of the List is LinkedList.
ArrayList provides constant-time random access, while LinkedList provides constant time for non-sequential access. When you declare a variable that will hold an ArrayList, consider accessing it through an interface, like this:
List<ElementType> myList = new ArrayList<ElementType>();
This will let you swap in a different implementation without disturbing the rest of your code.
List merely describes the contract of what it means to be a list. As such, it is not a concrete implementation but merely an interface. A list can be implemented in a number of ways.
In particular, you have ArrayList, which internally keeps a dynamic array for storing all the elements in order. You also have LinkedList, which stores elements as a doubly linked list i.e. a sequence of nodes which keep references to the previous and next nodes.
Vector is another List, much like an ArrayList in that its implementation is based on a dynamic array; it's, however, a relic of the older versions of Java and is guaranteed to be thread-safe by being wholly synchronized. In practice, new Vector<T>() is more-or-less equivalent to Collections.synchronizedList(new ArrayList<T>()).
The reason for having a List is that a list can come implemented in a number of ways. That being said, often you want to have some sort of generic behavior that can be applicable to all Lists... see polymorphism.
A List is an interface, and an ArrayList is an implementation of that interface. An ArrayList is a List, and so are LinkedLists, Stacks, Vectors, etc.
the other posters already answered the "what" part of your question. Some considerations to think about when choosing between them.
An ArrayList uses an array behind the scenes. So accessing by index can be done in constant time. Adding can also be done in constant time, if the array has been allocated with enough space. However, when the space runs out, ArrayList will allocate a larger array and copy the old array values into the new one.
A LinkedList uses nodes that are chained together. Accessing by an index can potentially require walking the entire list (linear time). Inserting only requires creating a new node and adding it at the end (which could be constant time if a tail pointer is maintained).
So "which one is better" can depend on how you are using it. Truthfully, I've never measured performance differences between the two, but it's just something to consider.
I know there is a InnerClass named"Itr" in java.util.AbstractList. and there is a field named "expectedModCount", a method named "checkForComodification". when iterator a collection but update the collection, this method will throw the ConcurrentModificationException
I want to know why java language designed like this? what is the purpose to do like this.
Thx !
I want to know why java language designed like this?
It's not part of the language. It's part of the collection framework.
Basically, it's relatively hard to make a very general specification about what should happen if you're iterating over a collection and it changes underneath you. While you could certainly decide on some rules for a list, what about (say) the entry set for a map? Adding or removing entries could change the internal order entirely - what would you want to happen then?
If it was allowed to change the collection you get a lot of problematic casses.
Say we have a list with elements 0 to 4
the iterator is just passed 3
|0|1|2|3|4|
iterator^
now we add an element at the begining
|5|0|1|2|3|4|
iterator^?^
What should the iterator return now?
it could return 4 since that was the next element before the change
it could return 3 since that is now at the index where the iterator was pointing at
Depending on the list implementation each of these also adds complexity and has a performance penalty, by forbidding the modification of collections we can avoid the specifying a correct behavior and the attached complexity.
You can iterate over a collection and modify it using Iterator (which is the standard way to do this).
See Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop for more discussion around this.
If a collection is modified by one thread while another reads from it, there might happen what we call a Race Condition . Avoiding it costs some performance, but you avoid unpredictable/unwanted results (e.g. you might skip or read twice an existing element in an ArrayList if there was no such check).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between ArrayList and Vector?
If I want to store some objects in a data collection and I have to choose between an ArrayList or a Vector, what are the main differences? I think vector are thread-safe and therefore have a performance penalty. Are there any other reasons to prefer on of the data containers?
Vector is a very old class from before the introduction of the Collections framework, therefore its API is polluted with many legacy methods that duplicate the methods from the Collection and List interface.
I'd generally avoid using it unless you have to because another API you're using demands it.
In short main difference between Vector and ArrayList is that Vector is synchronized while ArrayList is not. So, if multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
These two url's will be helpful to you. http://javarevisited.blogspot.com/2011/09/difference-vector-vs-arraylist-in-java.html and
http://geekexplains.blogspot.com/2008/05/difference-between-vector-and-arraylist.html
You have said it yourself. All the methods in Vector are painfully synchronized. Synchronization over a collection if required can be applied outside the class, preferably on case by case basis.
One more subtle difference between ArrayList and Vector is that you can control how the Vector can grow. Whereas in Arraylist, the size of internal array always doubles