Google Website Translator Gadget

Mostrando entradas con la etiqueta SortSet. Mostrar todas las entradas
Mostrando entradas con la etiqueta SortSet. Mostrar todas las entradas

jueves, 28 de marzo de 2013

Java 7: TreeSet add error

Quan programes, qualsevol detall es molt important.

Si detectes que al afegir un objecte a la llista, aquest no s'afegeix, revisa els següents punts:


TreeSet (http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html) permet la creació de conjunts ordenats d'objectes. Amb la funció add es permet afegir objectes al conjunt.

add(E e)
Adds the specified element to this set if it is not already present.

En el cas que sigui un objecte creat per tu, cal generar una funció CompareTo (http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html) que permeti saber si l'objecte existeix o no.

int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

En el meu cas particular, he perdut 1 dia de feina per un error en la implementació de la funció de comparació d'un objecte. A veure si descobreixes on es l'error d'implementació:


if (IDUsuari!=null && pUsuari.IDUsuari!=null)
{ IDUsuari.compareToIgnoreCase(pUsuari.IDUsuari);}

Un cop revisat les diferents funcionalitats, t'adonaràs que el resultat de la comparació no es retorna!! . Vet aquí! l'error que tant va costar trobar!

Assegura't que la funció de comparació retorna correctament el valor de comparació.



miércoles, 14 de noviembre de 2012

Java 7: SortSet implementation and example

Un cop revisat les diferents funcionalitats i implementacions de les Collections i els SortSet (veure entrada Collections i sortset ) i presa la decisió de implementar un SortSet voldràs veure un exemple.
Habitualment els exemples que es troben a Internet son exemples trivials amb tipus natius (int, char, ...).
Si treballes amb objectes complexos cal tenir en compte els següents detalls.

AccióExample
La classe ha de implementar Comparableclass P0102UsuariDetail
implements Comparable <P0102UsuariDetail>
El procediment ha de retornar un int
public int compareTo(P0102UsuariDetail pUsuari)
{
int result = UsuariID.compareTo(pUsuari.UsuariID);
return result;
}
Ja es pot declarar la el SortSetprivate TreeSet <P0102UsuariDetail> P0102Llista
=new TreeSet<P0102UsuariDetail>();
I utilitzar les funcions heredadesusuariP02 = new P0102UsuariDetail(); ...
P02Llista
.add(usuariP02);

Que pasa si intentes utilitzar les funcions i no hi ha un compareTo?
Per defecte si no hi ha la funció de comparació (compareTo) obtindrás un error: ClassCastException
 definit com a:
ClassCastException - if the specified object's type prevents it from being compared to this object.


Informació addicional:
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html


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