Google Website Translator Gadget

domingo, 5 de febrero de 2012

Java 7: Collections i SortSet

Java logo
java.com
Perquè he arribat aquí?
Intentant trobar una forma millor per a enmagatezmar objectes ordenats dins d'un programa... i fallar espectacularment amb un aclaridor Exception in thread "main" java.lang.NullPointerException
Això em va fer posar a tornar a estudiar Collection i trobar aventatges addicionals a la versió Java7:
  • Set Interface Bulk Operations: Com s1.addAll(s2) — transforms s1 into the union of s1 and s2.
  • HashSet, which stores its elements in a hash table, is the best-performing implementation;

Collection are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).



The Set Interface
A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. The Java platform contains three general-purpose Set implementations:
HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.
 TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.
 LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering provided by HashSet at a cost that is only slightly higher.

Notes importants!!!
Les Collection s'han d'instanciar, però has de tenir en comte també les seves implementacions.
Així per exemple, per a implementar una Collection genèrica, pots agafar el HashSet:
Collection<Type> noDups = new HashSet<Type>(c);
o per a una llista has d'escollir entre ArrayList o LinkedList
List<Type> list3 = new ArrayList<Type>();

Enllaços relacionats:

http://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html
http://docs.oracle.com/javase/tutorial/collections/index.html
http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

No hay comentarios:

Publicar un comentario