1 / 20

Colecciones

Colecciones. Interface Collection. add(o) Añade un elemento nuevo clear() Elimina todos los elementos contains(o) Comprueba membresía IsEmpty() Comprueba si está vacío iterator() Devuelve un iterator remove(o) Elimina un elemento size() Número de elementos.

kineta
Download Presentation

Colecciones

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Colecciones

  2. Interface Collection • add(o) Añade un elemento nuevo • clear() Elimina todos los elementos • contains(o) Comprueba membresía • IsEmpty() Comprueba si está vacío • iterator() Devuelve un iterator • remove(o) Elimina un elemento • size() Número de elementos

  3. Interface List • add(i,o) Inserta o en la posición i • add(o) Añade o al final • get(i) Devuelve el i-ésimo elemento • remove(i) Eliminia e i-ésimo elemento • remove(o) Elimina el elemento o • set(i,o) Remplaza el i-ésimo elemento con o

  4. Interface Map • Clear() Elimina todos las asociaciones • containsKey(k) Si contiene una asoc. para k • containsValue(v) Si contiene una asoc. para v • SetentrySet() Conjunto de pares de valores clave • get(k) Valor asociado con k • isEmpty() Si está vacío • keySet() Conjunto de claves • put(k,v) Asociar v con k • remove(k) Eliminar asoc. para k • size() Número de pares • values() Colección de valores

  5. Colecciones concretas colección implementa descripción concreta HashSet Set hash table TreeSet SortedSet balanced binary tree ArrayList List resizable-array LinkedList List linked list Vector List resizable-array HashMap Map hash table TreeMap SortedMap balanced binary tree Hashtable Map hash table

  6. Iterar sobre solecciones interface Iterator : interface Iterator { boolean hasNext(); Object next(); void remove(); } El método iterator() definido en la interface Collection: Iterator iterator()

  7. Uso de Set Set set = new HashSet(); // instancia de un set concreto // ... set.add(obj); // inserta elementos // ... int n = set.size(); // obtiene tamaño // ... if (set.contains(obj)) {...} // verifica miembro // iterata a través del set Iterator iter = set.iterator(); while (iter.hasNext()) { Object e = iter.next(); // downcast e // ... }

  8. Uso de Map Map map = new HashMap(); // instancia un map concreto // ... map.put(key, val); // inserta par llave-valor // ... // obteiene el valor asociado a la llave Object val = map.get(key); map.remove(key); // elimina par llave-valor // ... if (map.containsValue(val)) { ... } if (map.containsKey(kay)) { ... } Set keys = map.keySet(); // obtiene el conjunto de llaves // iterata a través del conjunto de llaves Iterator iter = keys.iterator(); while (iter.hasNext()) { Key key = (Key) iter.next(); // ... }

  9. Cuenta palabras diferentes (I) import java.util.*; import java.io.*; public class CuentaPalabras { static public void main(String[] args) { HashSet words = new HashSet(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String delim = " \t\n.,:;?!-/()[]\"\'"; String line; int count = 0;

  10. Cuenta palabras diferentes (II) try { while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, delim); while (st.hasMoreTokens()) { count++; words.add(st.nextToken().toLowerCase()); } } } catch (IOException e) {} System.out.println("Numero total de palabras: " + count); System.out.println("Numero de palabras diferentes : " + words.size()); } }

  11. Frecuencia Palabras (I) static class Count { Count(String word, int i) { this.word = word; this.i = i; } String word; int i; }

  12. Frecuencia Palabras (II) import java.util.*; import java.io.*; public class FrecuenciaPalabras { static public void main(String[] args) { HashMap words = new HashMap(); String delim = " \t\n.,:;?!-/()[]\"\'"; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line, word; Count count;

  13. Frecuencia Palabras (III) try { while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, delim); while (st.hasMoreTokens()) { word = st.nextToken().toLowerCase(); count = (Count) words.get(word); if (count == null) { words.put(word, new Count(word, 1)); } else { count.i++; } } } } catch (IOException e) {}

  14. Frecuencia Palabras (IV) Set set = words.entrySet(); Iterator iter = set.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); word = (String) entry.getKey(); count = (Count) entry.getValue(); System.out.println(word + (word.length() < 8 ? "\t\t" : "\t") + count.i); } } }

  15. Orden y ordenamiento • Hay dos formas de definir orden entre objetos. • Cada clase puede definir un orden natural entre sus instancias implementando la interface Comparable. int compareTo(Object o) • Un orden arbitrario entre diferentes objetos se puede definir por comparadores, clases que implementan la interface Comparator. int compare(Object o1, Object o2)

  16. Frecuencia Palabras2 public class FrecuenciaPalabras2 { static public void main(String[] args) { TreeMap words = new TreeMap(); .... < igual a FrecuenciaPalabras> } }

  17. Orden definido por el usuario • Orden alfabético inverso de cadenas: public class StringComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 != null && o2 != null && o1 instanceof String && o2 instanceof String) { String s1 = (String) o1; String s2 = (String) o2; return - (s1.compareTo(s2)); } else { return 0; } } }

  18. Frecuencia Palabras2_1 public class FrecuenciaPalabras2_1 { static public void main(String[] args) { TreeMap words = new TreeMap(new StringComparator( )); .... < igual a FrecuenciaPalabras2> }

  19. Ordenamiento static class CountComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 != null && o2 != null && o1 instanceof Count && o2 instanceof Count) { Count c1 = (Count) o1; Count c2 = (Count) o2; return (c2.i - c1.i); } else { return 0; } } }

  20. Frecuencia Palabras3 public class FrecuenciaPalabras3{ static public void main(String[ ] args) { < igual a FrecuenciaPalabras2> List list = new ArrayList(words.values()); Collections.sort(list, new CountComparator()); Iterator iter = list.iterator(); while (iter.hasNext()) { count = (Count) iter.next(); word = count.word; System.out.println(word + (word.length() < 8 ? "\t\t" : "\t") + count.i); } } }

More Related