9. 1. 4. Conversion of different Collection data types |
|
Implementations of the Collection interface normally have a constructor that accepts a Collection object.
This enables you to convert a Collection to a different type of Collection, such as a Queue to a List, or a List to a Set, etc. Here are the constructors of some implementations: |
public ArrayList (Collection c)
public HashSet (Collection c)
public LinkedList (Collection c)
|
|
As an example, the following code converts a Queue to a List. |
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class MainClass {
public static void main(String[] args) {
Queue queue = new LinkedList();
queue.add("Hello");
queue.add("World");
List list = new ArrayList(queue);
System.out.println(list);
}
}
|
|
[Hello, World] |
And this converts a List to a Set. |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainClass {
public static void main(String[] args) {
List myList = new ArrayList();
myList.add("Hello");
myList.add("World");
myList.add("World");
Set set = new HashSet(myList);
System.out.println(set);
}
}
|
|
[World, Hello] |