понеділок, 2 лютого 2015 р.

Java:Collection

Collection/container:



  • object that groups multiple elements; 
  • used to store, retrieve, manipulate, communicate aggregate data

In short main difference between List and Set in Java is that List is an ordered collection which allows duplicates while Set is an unordered collection which doesn't allow duplicates.

LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations for add, poll, and so on.

Set
There are three general-purpose Set implementations — HashSet, TreeSet, and LinkedHashSet. Which of these three to use is generally straightforward. HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees. If you need to use the operations in the SortedSet interface, or if value-ordered iteration is required, use TreeSet; otherwise, use HashSet. LinkedHashSet is in some sense intermediate between HashSet and TreeSet.

public class HashSetDemo {

 public static void main(String args[]) {
 // create a hash set

 LinkedHashSet hs = new LinkedHashSet();
 // add elements to the hash set 
 hs.add("B");
 hs.add("A");
 hs.add("D");
 hs.add("E");
 hs.add("C");
 hs.add("F");
hs.add("F");
hs.add(“A");
System.out.println(hs);

 } }

List
There are two general-purpose List implementations — ArrayList and LinkedList. ArrayList is usually faster.

public class CollectionsDemo {

public static void main(String[] args) { 

List<String> a1 = new ArrayList<String>(); 
a1.add("Zara"); 
a1.add("Mahnaz"); 
a1.add("Ayan"); 
System.out.println(" ArrayList Elements"); 
System.out.print("\t" + a1); 

List<String> l1 = new LinkedList<String>(); 
l1.add("Zara"); 
l1.add("Mahnaz");
l1.add("Ayan"); 
System.out.println(" LinkedList Elements"); 
System.out.print("\t" + l1);

Map
The three general-purpose Map implementations are HashMap, TreeMap and LinkedHashMap. If you need SortedMap operations or key-ordered Collection-view iteration, use TreeMap; if you want maximum speed and don't care about iteration order, use HashMap; if you want near-HashMap performance and insertion-order iteration, use LinkedHashMap. In this respect, the situation for Map is analogous to Set. 

public class CollectionsDemo {

public static void main(String[] args) { 

Map<String, String> m1 = new HashMap<String, String>(); 
m1.put("Zara", "8"); 
m1.put("Mahnaz", "31"); 
m1.put("Ayan", "12"); 
m1.put("Daisy", "14"); 
System.out.println(" Map Elements"); System.out.print("\t" + m1);

for(Entry<String, String> e : m1.entrySet()) { 
String key = e.getKey(); 
String value = e.getValue(); 

Queue
As mentioned in the previous section, LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations for add, poll, and so on.


Немає коментарів:

Дописати коментар