PROGRAMACIÓN ORIENTADA A OBJETOS PROGRAMACIÓN ORIENTADA A OBJETOS. CONTAINERS (o COLLECTIONS) TEMA4: Más Collections: Conjuntos y Mapas

Documentos relacionados
Tema 4 Colecciones en Java. Programación Orientada a Objetos Curso 2013/2014

EL PAQUETE JAVA.UTIL DEL API JAVA. PRINCIPALES INTERFACES Y CLASES: STRINGTOKENIZER, DATE, CALENDAR, HASHSET, TREEMAP, TREESET...

Colecciones de Java LSUB. 17 de febrero de 2016 GSYC

Unidad Didáctica 2. Elementos básicos del lenguaje Java Tipos, declaraciones, expresiones y asignaciones

Fun with infinitives

CONTROLADORA PARA PIXELS CONPIX

Java Básico. Estructuras de Datos 2. Copyright

PROGRAMACION ORIENTADA A OBJETOS Ingenieria Informática Final Febrero 2006/07

Manual para Cambio de Apariencia en Acrobat Reader DC. Change of Appearance in Acrobat Reader DC

Tutorial 11. Temas. Búsqueda Clasificación Estructura de Java Collection Problemas del tutorial Ejercicios de diseño. Búsqueda

Lenguajes de Programación Curso Práctica 4. Herencia. Utilización de interfaces y clases abstractas. 1. Interfaces Clases abstractas 2

INTERFACES SET Y SORTEDSET DEL API DE JAVA. CLASES HASHSET Y TREESET. EJEMPLO. DIFERENCIAS ENTRE ELLAS. (CU00921C)

Contenido. Prólogo... Capítulo 1. Algoritmos y estructuras de datos Introducción... 24

INTERFACE COMPARATOR. DIFERENCIAS ENTRE COMPARATOR Y COMPARABLE. CLASE COLLECTIONS. EJERCICIOS RESUELTOS. (CU00918C)

C.I.F.: B Inscrita en el Registro Mercantil de Madrid, Tomo Libro 0, Folio 135, Sección 8. Hoja M Inscripción 1ª

Prof. Aidsa Santiago. Cesar A Aceros Moreno

PARA QUÉ SIRVEN LAS INTERFACES JAVA. IMPLEMENTAR UNA INTERFAZ DEL API. VENTAJAS. EJEMPLOS BÁSICOS. (CU00697B)

Agustiniano Ciudad Salitre School Computer Science Support Guide Second grade First term

LA DONCELLA DE LA SANGRE: LOS HIJOS DE LOS ANGELES CAIDOS (LOS HIJOS DE LOS NGELES CADOS) (VOLUME 1) (SPANISH EDITION) BY AHNA STHAUROS

Colecciones. Nadjet Bouayad-Agha Programación 2007

fundamentos de programación (unidad 7) herencia y relaciones entre clases

Listening exercise. Instructions: they have to work in groups of three. This is the link of the video clip.

EL PODER DEL PENSAMIENTO FLEXIBLE DE UNA MENTE RAGIDA A UNA MENTE LIBRE Y ABIERTA AL CAMBIO BIBLIOTECA WALTER

Gender, Definite, & Indefinite Articles Making things plural

Árboles binarios de búsqueda

Learning Masters. Early: Force and Motion

public static void main(string[ ] args) { Numero f1 = new Numero(3); Numero f2 = new Numero(4); Numero f3 = f1; f1.value = f2.value; Numero f4 = null;

Los seres vivos/ living things. CONOCIMIENTO DEL MEDIO 3º DE PRIMARIA

Ordenación de colecciones de objetos.

Objective: To create a Celebrity Family Tree by MAKING LINKS and THINKING CREATIVELY!

Unidad Didáctica 6. Tipos List y Set con tipos genéricos. Fundamentos de Programación Departamento de Lenguajes y Sistemas Informáticos. Versión 1.0.

Tema 3: Herencia en Java. Programación Orientada a Objetos Curso 2009/2010 Begoña Moros Valle

CUANDO LA MUSA SE HACE VERBO VERSOS CORTOS POEMAS DE AMOR POEMAS DE DESAMOR Y POEMAS CORTOS SPANISH EDITION

In English, present progressive can be used to describe what is happening now, or what will happen in the future.

Programación Orientada a Objetos Curso 2015/2016. Ejercicios sobre colecciones y Java 8

ADOBE ILLUSTRATOR AVANZADO PDF

Clase 33. Marco para las colecciones de Java. Historia

Prácticas de Programación

INDICE DEL CURSO APRENDER PROGRAMACIÓN JAVA DESDE CERO. PROGRAMACIÓN ORIENTADA A OBJETOS (CU00601B)

Grados Ing. Inf. y Mat. Inf. Julio 2014 Algoritmos y Estructura de Datos Página 1 de 6

TELEVISOR A COLORES MANUAL DE SERVICIO MODELO : CP-29C40P. ATENCIÓN Antes de dar servicio al chasis, lea las PRECAUCIONES DE SEGURIDAD en este manual.

Tema 3: Genericidad en Java. Tema 3: Genericidad en Java. Objetivos y Bibliografía. Modelos de Datos Genéricos

Titulación: Ingeniero Técnico en Informática de Gestión Curso: 2º

Introducción a Java LSUB. 30 de enero de 2013 GSYC

An explanation by Sr. Jordan

Problemas de Optimización: una Introducción

Level 1 Spanish, 2013

ÍNDICE DEL LIBRO Y DEL EBOOK APRENDER A PROGRAMAR EN JAVA DESDE CERO. CURSO PASO A PASO.

Chattanooga Motors - Solicitud de Credito

Nouns: Countable & Uncountable nouns (a bottle /some water)

Variables. Una variable no es más que un nombre simbólico que identifica una dirección de memoria: vs.

74 Prime Time. conjetura Suposición acerca de un patrón o relación, basada en observaciones.

Repaso de funciones exponenciales y logarítmicas. Review of exponential and logarithmic functions

TECHNOLOGY ENHANCED LANGUAGE LEARNING MODULE Module on Las partes del cuerpo humano

Organización de Aviación Civil Internacional GRUPO DE EXPERTOS SOBRE MERCANCÍAS PELIGROSAS (DGP) VIGESIMOQUINTA REUNIÓN

Rubric for Family Tree

Agradecimientos. Nota de los autores. 1 Problemas, algoritmos y programas 1

The December Family Engineering Challenge K-2

Introducción a ZEUS. Introducción. Curso Doctorado Sistemas Multi-agente. Zeus es una herramienta de desarrollo de SMA.

Práctica Autenticación y Autorización en GLITE

Patrones de diseño. Patrón básico Handler. Técnicas de Programación - Curso 2008/09 (Esther Guerra Sánchez)

Programación orientada a objetos. Resumen de Temas Unidad 5: Herencia

Objetivo: You will be able to You will be able to

SHIELD DE EXTENSIÓN CON ENTRADAS ANALÓGICAS

Matemáticas Muestra Cuadernillo de Examen

Introducción a la Ingeniería de Software. Diseño Interfaz de Usuario

Final Project (academic investigation)

SEO Lite. Extract the file SEO.zip in the modules folder, so that module files are inside /moules/ seo/.

Brief Introduction to Docking and Virtual Screening with Autodock4 and Autodock Tools

IRS DATA RETRIEVAL NOTIFICATION DEPENDENT STUDENT ESTIMATOR

DICCIONARIO MANUAL BIBLICO PDF

ASI HABLO ZARATUSTRA UN LIBRO PARA TODOS Y PARA NADIE SPANISH EDITION

Centro Asociado Palma de Mallorca. Antonio Rivero Cuesta

Tema 2. Técnicas básicas de POO. Técnicas de Programación - Curso 2007/08

Construcciones del Lenguaje Java

Summer Reading Program. June 1st - August 10th, 2015

Estación Uno: Date, Weather, and How you feel

MANUSCRITOS ECONOMICOS MARX PDF

Licenciatura en Contaduría. Inglés V

Learning Masters. Fluent: Wind, Water, and Sunlight

Tutorial 1: Desarrollo de un plugin

Guide to Health Insurance Part II: How to access your benefits and services.

vosotras= vosotros= él= ellos= ella= ellas= usted= ustedes= Subject pronouns are used as the subject of a sentence. In general, they tell who is being

lunes, 10 de noviembre 2014

Java J2SE Standard Programming

Will (2) Will (2) When we talk about the future, we often say what someone has arranged to do or intend to do. Do not use will in this situation:

Carmen: No, no soy Mexicana. Soy Colombiana. Y tú? Eres tú Colombiano?

(GUÍA_DE_ESTUDIO) Recuerda los verbos regulares y stem-changing verbs.

Manual de configuración de Replicación Multimaster en servidores Ldap

Introducción al desarrollo de RIA's con Adobe Flex 3.0 Dia 4

Study Packet for the Regents Exam (5 pages)

VECTORES. MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

El Cuarto Misterioso Episodio 6 Narrativa

Telling Time in Spanish Supplemental Hand-out

Shortcut to Informal Spanish Conversations Level 2 Lesson 1

Me Duele Review Packet

Y UN DIA DEJE DE FUMAR PDF

El condicional Recordatorio: Conditional is used for 2 purposes.

MANUAL EASYCHAIR. A) Ingresar su nombre de usuario y password, si ya tiene una cuenta registrada Ó

programa. Hoy nuestros invitados son un camello y su cuidador. Cuál es el hábitat de este animal? no necesitan beber agua con frecuencia.

Transcripción:

PROGRAMACIÓN ORIENTADA A OBJETOS PROGRAMACIÓN ORIENTADA A OBJETOS TEMA4: Más Collections: Conjuntos y Mapas Manel Guerrero Antes que nada veamos W4H1 Para repasar Comparable. CONTAINERS (o COLLECTIONS) java.lang.object + java.util.abstractcollection<e> + java.util.abstractlist<e> + ArrayList (*) + AbstractSequentialList + LinkedList (*) + java.util.abstractset<e> + java.util.hashset<e> (*) + java.util.treeset<e> (*) + java.util.abstractqueue<e> +... + java.util.abstractmap<k,v> + java.util.hashmap<k,v> (*) + java.util.treemap<k,v> (*) La imagen anterior o es de una versión anterior o contiene errores. Esta es la versión correcta de la JavaSE8. En el tema anterior vimos las listas. Ahora veremos los conjuntos (sets) y los diccionarios o mapas (maps).

Conjuntos (Sets) No hay un orden (como en las listas). No pueden haber elementos duplicados. Utilizaremos HashSet cuando los elementos no tienen un orden. TreeSet cuando los elementos son comparables (implementan la interface Comparable). Si nos da igual, HashSet es más eficiente. Veamos ahora W4H2. Diccionarios (Maps) En lugar de guardar elementos <E>, guardan parejas de clave y valor <K,V>. Como en un diccionario donde tenemos <palabra,definición>. Las claves no pueden estar repetidas. Tienen que ser únicas. Se pueden usar cuando un atributo de V es único. Ejemplo: <NIF,persona>. Igual que con los Sets, utilizaremos HashSet cuando no necesitemos ordenar los elementos. TreeSet cuando necesitemos ordenarlos. Veamos ahora W4H3 y W4H4. Iterando por una lista Iterando por una lista (casting requerido) Iterator<Book> it = llista.iterator(); while(it.hasnext()){ Book b = it.next(); if(b.getisbn().equals(my_book){ System.out.println(b); break; // En el ejemplo anterior: // Iterator<Book> it = llista.iterator(); Iterator it = llista.iterator(); while(it.hasnext()){ Book b = (Book) it.next(); if(b.getisbn().equals(my_book)){ System.out.println(b); break; Aquí hace falta un casting porque no hemos indicado que el iterador era de Books. En el ejemplo anterior habíamos declarado el iterador como Iterator<Book>.

Enhanced for for collections Enhanced for for collections (2) For lists and sets: for(book b : set) For maps: for(book b : map.values()) for(string isbn : map.keys()) for(map.entry<string, Book> entry : map.entryset()) El for-each en un mapa tanto se puede hacer: Por valor. Por clave. Por entry (pareja <clave,valor>). Si iteras por entry puedes acceder tanto a la clave como al valor: Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entryset()) { System.out.println("Key = " + entry.getkey() + ", Value = " + entry.getvalue()); Pero si solo quieres las claves o el valor: for (Integer k : map.keyset()) for (Integer v : map.values()) TreeSet, TreeMap y Comparable Tree: Árboles rojo-negro To use TreeSet<Dog>, Dog (<E>) has to be Comparable. To use TreeMap<Key,Dog>, Key (<K>) has to be Comparable. class Dog implements Comparable<Dog>{ String color; int size; [...] @Override public int compareto(dog o) { return o.size this.size; Los TreeSet y TreeMap están implementados como árboles rojo-negro: un tipo de árbol binario de búsqueda. Por tanto las operaciones de acceso, inserción y borrado son complicadas, pero sus tiempos de ejecución son O(log n). Y sus elementos están siempre ordenados. Para ordenarlas usa el compareto() (por tanto hay que implementar la interface Comparable) y el equals() (por tanto hay que override el equals() de la clase Object).

Hash: Tablas de Hash Interfaces, abstract and concrete classes of collections Los HashSet y HashMap están implementados como tablas de hash. Por tanto las operaciones de acceso, inserción y borrado tienen tiempos de ejecución constante si la función de hash distribuye correctamente. Y sus elementos no están ordenados. En una clase podremos override el public int hashcode() de la clase Object. Pero normalmente no será necesario. https://www.cs.cmu.edu/~pattis/15-1xx/15-200/lectures/collectionsiii/lecture.html Interfaces, abstract and concrete classes of collections (2) Interfaces, abstract and concrete classes of collections (3)

The difference between an Interface and an Abstract class Methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behaviour. [No del todo cierto desde Java8] Variables declared in a Java interface are by default final. Members of a Java interface are public by default. A Java interface should be implemented using keyword implements ; A Java abstract class should be extended using keyword extends. A Java class can implement multiple interfaces but it can extend only one abstract class. http://stackoverflow.com/questions/18777989/how-should-i-haveexplained-the-difference-between-an-interface-and-an-abstract The difference between an Interface and an Abstract class (2) An interface is a description of the behaviour an implementing class will have. The implementing class ensures, that it will have these methods that can be used on it. It is basically a contract or a promise the class has to make. An abstract class is a basis for different subclasses that share behaviour which does not need to be repeatedly created. Subclasses must complete the behaviour and have the option to override predefined behaviour (as long as it is not defined as final or private). Unrelated classes can have [same] capabilities through interface but related classes change the behaviour through extension of base classes. The difference between an Interface and an Abstract class (3) You will find good examples in the java.util package which includes interfaces like List and abstract classes like AbstractList which already implements the interface. The official documentation describes the AbstractList as follows: This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). The difference between an Interface and an Abstract class (4) An interface consists of singleton variables (public static final) and public abstract methods. We normally prefer to use an interface in real time when we know what to do but don't know how to do it. We choose an abstract class when there are some features for which we know what to do, and other features that we know how to [do it].

PROGRAMACIÓN ORIENTADA A OBJETOS Preguntas