| Start |
|---|
| Removing items from a List within a loop It is tricky to remove items from a list while within a loop, this is due to the fact that the index and length of the list gets changed. Given the following list, here are some examples that will give an unexpected result and some that will give the correct result. INCORRECT Removing in iteration of |
Constructing collections from existing data Standard CollectionsJava Collections frameworkA simple way to construct a All standard collection implementations provide constructors that take another collection as an argument adding all elements to the new collection at the time of construction: Google Guava Collections frameworkAnother great framework is Mapping CollectionsJava Collections frameworkSimilarly for maps, given a Apache Commons Collections frameworkUsing Each element of the array must be either a Map.Entry or an Array, containing at least two elements, where the first element is used as key and the second as value. Google Guava Collections frameworkUtility class from Using or |
| Declaring an ArrayList and adding objects We can create an Now, use the method In the above example, the Also we can add multiple elements with Now "Onion" is placed at 0 index in |
Iterating over Collections Iterating over ListIf we need parallelism use Iterating over SetIterating over Map |
| Immutable Empty Collections Sometimes it is appropriate to use an immutable empty collection. The These methods are generic and will automatically convert the returned collection to the type it is assigned to. That is, an invocation of e.g. The collections returned by these methods are immutable in that they will throw |
| Unmodifiable Collection Sometimes it's not a good practice expose an internal collection since it can lead to a malicious code vulnerability due to it's mutable characteristic. In order to provide "read-only" collections java provides its unmodifiable versions. An unmodifiable collection is often a copy of a modifiable collection which guarantees that the collection itself cannot be altered. Attempts to modify it will result in an UnsupportedOperationException exception. It is important to notice that objects which are present inside the collection can still be altered. The following attempt to modify an unmodifiable collection will throw an exception: output: |
| Pitfall: concurrent modification exceptions This exception occurs when a collection is modified while iterating over it using methods other than those provided by the iterator object. For example, we have a list of hats and we want to remove all those that have ear flaps: If we run this code, ConcurrentModificationException will be raised since the code modifies the collection while iterating it. The same exception may occur if one of the multiple threads working with the same list is trying to modify the collection while others iterate over it. Concurrent modification of collections in multiple threads is a natural thing, but should be treated with usual tools from the concurrent programming toolbox such as synchronization locks, special collections adopted for concurrent modification, modifying the cloned collection from initial etc. |
Sub Collections List subList(int fromIndex, int toIndex)Here fromIndex is inclusive and toIndex is exclusive.
Example: Output: Set subSet(fromIndex,toIndex)Here fromIndex is inclusive and toIndex is exclusive. The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range. Map subMap(fromKey,toKey)fromKey is inclusive and toKey is exclusive If fromKey is greater than toKey or if this map itself has a restricted range, and fromKey or toKey lies outside the bounds of the range then it throws IllegalArgumentException. All the collections support backed collections means changes made on the sub collection will have same change on the main collection. |
| Join lists Following ways can be used for joining lists without modifying source list(s). First approach. Has more lines but easy to understand Second approach. Has one less line but less readable. Third approach. Requires third party Apache commons-collections (opens new window) library. Using Streams the same can be achieved by References. Interface List (opens new window) |
| Removing matching items from Lists using Iterator. Above I noticed an example to remove items from a List within a Loop and I thought of another example that may come in handy this time using the Note: This is only adding on to the Removing items from a List within a loop example: So let's define our lists as usual The following method takes in two Collection objects and performs the magic of removing the elements in our Calling the method and passing in the Array List before removing names:
**James Smith Sonny Huckle Berry Finn Allan** A simple neat use for Collections that may come in handy to remove repeating elements within lists. |
| Collections and Primitive Values Collections in Java only work for objects. I.e. there is no Unfortunately, the overhead of this is substantial. A There exist several libraries with optimized collections for primitive data types (that require only ~16 bytes per entry at 50% load, i.e. 4x less memory, and one level of indirection less), that can yield substantial performance benefits when using large collections of primitive values in Java. |
| Creating your own Iterable structure for use with Iterator or for-each loop. To ensure that our collection can be iterated using iterator or for-each loop, we have to take care of following steps: I have added a simple generic linked list implementation below that uses above entities to make the linked list iterable. Output This will run in Java 7+. You can make it run on Java 5 and Java 6 also by substituting: with or just any other version by incorporating the compatible changes. RemarksCollections are objects that can store collections of other objects inside of them. You can specify the type of data stored in a collection using Generics (opens new window). Collections generally use the Java 1.4.2 and below do not support generics. As such, you can not specify the type parameters that a collection contains. In addition to not having type safety, you must also use casts to get the correct type back from a collection. In addition to
Java 5 adds in a new collection type:
Java 6 adds in some new subtypes of collections.
Note that the above items are all interfaces. In order to use them, you must find the appropriate implementing classes, such as Each type of collection has multiple implementations that have different performance metrics and use cases. Note that the Liskov Substitution Principle (opens new window) applies to the collection subtypes. That is, a If you want to create your own collections, it may be easier to inherit one of the abstract classes (such as Prior to 1.2, you had to use the following classes/interfaces instead:
These classes are obsolete and should not be used in modern code. |
Read Article
https://develop.horje.com/learn/1434/reference