You are on page 1of 7

4 uujuju3242 invstigacion

Java collections

The Collection in Java is a framework that provides an architecture to store and


manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet).

o What are the two ways to iterate the elements of a collection?


o What is the difference between ArrayList and LinkedList classes in collection
framework?
o What is the difference between ArrayList and Vector classes in collection
framework?
o What is the difference between HashSet and HashMap classes in collection
framework?
o What is the difference between HashMap and Hashtable class?
o What is the difference between Iterator and Enumeration interface in collection
framework?
o How can we sort the elements of an object? What is the difference between
Comparable and Comparator interfaces?
o What does the hashcode() method?
o What is the difference between Java collection and Java collections?
o En java existen 4 pilares básicos para la programación orientada a Objetos, de entre los
cuales encontramos:
o
o Encapsulamiento: es la forma en la que podemos definir como se visualiza la
información o como será oculta, esto para la seguridad de la misma, un atributo
principalmente aparece como un campo público, pero podemos volverlo Privado o en
su defecto para otras cosas dejarlo protegido.(Figure 1)
Encapsulamiento (Figure 1)
o
o
o Herencia: es una manera de reutilizar código, pero se define como la capacidad que
tiene una clase padre de heredad sus atributos y métodos a una clase hija, y aunque
hereda los atributos la clase hija tiene atributos propios. En java no existe la multi-
herencia por lo cual se hace un proceso de interfaces que se asimila a loa que es una
herencia múltiple sin embargo no es lo mismo. (Figure 2)
o
o

Herencia (Figure 2)
o
o Polimorfismo: Se refiere a la posibilidad de definir clases diferentes que tienen
métodos o atributos denominados de forma idéntica pero se comportan diferente.
(Figure 3)
Polimorfismo (Fig
10 public boolean containsAll(Collection<?> c) It is used to search
the specified collection in the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array.


Here, the runtime type of the returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel


Stream with the collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the


collection as its source.

17 default Spliterator<E> spliterator() It generates a Spliterator over


the specified elements in the collection.

18 public boolean equals(Object element) It matches two collections.

19 public int hashCode() It returns the hash code number of the


collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in a forward


direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
No. Method Description

1 public boolean hasNext() It returns true if the iterator has more


elements otherwise it returns false.

2 public Object next() It returns the element and moves the cursor
pointer to the next element.

3 public void remove() It removes the last elements returned by the


iterator. It is less used.

Iterable Interface

The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the
subclasses of Collection interface also implement the Iterable interface.

Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all
the subclasses of Collection interface.

List Interface
Los tres pilares del desarrollo orientado a objetos son la encapsulación, la herencia y el
polimorfismo. Si... ya veo que en la imagen aparece también abstracción... no seas cansino.

La abstracción:

Mucha gente considera que la abstracción en si no es más que una parte del proceso de la
encapsulación, y por tanto no la tienen como pilar independiente de la POO.
La abstracción es la capacidad de obtener y aislar toda la información y cualidades de un objeto que
no nos
, ya que solo le interesan algunas, como el precio.

Poniendo un ejemplo de videojuegos. Si creamos un juego de coches tipo Arcade, lo único que
necesitamos abstraer de un coche real serán cosas como, la forma, el color y la velocidad, por
ejemplo. Pero, si queremos crear un juego de coches tipo simulador, deberemos abstraer muchas
más cosas, como el peso, la potencia, el tipo de tracción, tipo de combustible, tipo de ruedas, etc...

La encapsulación:

La encapsulación es la capacidad de ocultar los datos abstraídos, aislarlos o protegerlos de quién


no desees que tenga acceso a ellos; otro objeto o función por ejemplo.
Cada objeto puede tener muchas cosas encapsuladas en su interior, propiedades, funciones o
incluso otros objetos.
Muchas veces no se necesita entender el funcionamiento interno de un objeto, sino tan solo sus
funcionalidades: para que sirve o qué puede hacer. Por tanto un objeto puede ser cambiado por otro
siempre que
cómo funciona internamente un coche, solo necesita saber que al pisar el acelerador (aplicar el método)
el coche anda.
Gewf4

Ejemplo Java
podría implementarla para comparar dos empleados.
La declaración de la clase empleado se modificaría a:
class Employee implements Comparable

La otro modificación es que la clase Employee debe implementar esta


función. Por ejemplo:
public int compareTo(Object otroObject)
{
Employee otro=(Employee) otroObject;
if (salary < otro.salary) return -1;
if (salary > otro.salary) return 1;
return 0;

Ejemplo Java

Sea al Interfaz Comparable.java


public interface Comparable
{
int compareTo(Object otro);
}

Luego la clase Employee podría implementarla para comparar dos


empleados.
La declaración de la clase empleado se modificaría a:
class Employee implements Comparable

1;
return 0;
}

Ver ejemplo EmployeeSortTest.java. Destacar invocación a Array.sort()


Java sólo permite heredar de una clase, pero permite implementar
múltiples interfaces.

Ver ejemplo TimerTest.java

You might also like