40 preguntas y respuestas de la entrevista sobre colecciones de Java

Java Collections Framework es una de las API principales del lenguaje de programación Java. Es uno de los temas importantes para las preguntas de entrevistas sobre Java. Aquí enumero algunas preguntas y respuestas importantes sobre colecciones de Java para ayudarte en la entrevista. Esto surge directamente de mis más de 14 años de experiencia en programación Java.

Preguntas de la entrevista sobre colecciones de Java

  1. ¿Cuáles son las características relacionadas con la colección en Java 8?
  2. ¿Qué es Java Collections Framework? ¿Cuáles son algunos de los beneficios de Collections Framework?
  3. ¿Cuál es el beneficio de los genéricos en Collections Framework?
  4. ¿Cuáles son las interfaces básicas de Java Collections Framework?
  5. ¿Por qué Collection no extiende las interfaces Cloneable y Serializable?
  6. ¿Por qué la interfaz de Mapa no extiende la interfaz de Colección?
  7. ¿Qué es un iterador?
  8. ¿Cuál es la diferencia entre la interfaz de enumeración y la de iterador?
  9. ¿Por qué no hay un método como Iterator.add() para agregar elementos a la colección?
  10. ¿Por qué Iterator no tiene un método para obtener el siguiente elemento directamente sin mover el cursor?
  11. ¿Cuál es la diferencia entre Iterator y ListIterator?
  12. ¿Cuáles son las diferentes formas de iterar sobre una lista?
  13. ¿Qué entiendes por propiedad de falla rápida del iterador?
  14. ¿Cuál es la diferencia entre fail-fast y fail-safe?
  15. ¿Cómo evitar ConcurrentModificationException al iterar una colección?
  16. ¿Por qué no hay implementaciones concretas de la interfaz Iterator?
  17. ¿Qué es UnsupportedOperationException?
  18. ¿Cómo funciona HashMap en Java?
  19. ¿Cuál es la importancia de los métodos hashCode() y equals()?
  20. ¿Podemos utilizar cualquier clase como clave de mapa?
  21. ¿Cuáles son las diferentes vistas de colección que ofrece la interfaz de Mapa?
  22. ¿Cuál es la diferencia entre HashMap y Hashtable?
  23. ¿Cómo decidir entre HashMap y TreeMap?
  24. ¿Cuáles son las similitudes y diferencias entre ArrayList y Vector?
  25. ¿Cuál es la diferencia entre Array y ArrayList? ¿Cuándo se debe utilizar Array en lugar de ArrayList?
  26. ¿Cuál es la diferencia entre ArrayList y LinkedList?
  27. ¿Qué clases de colección proporcionan acceso aleatorio a sus elementos?
  28. ¿Qué es EnumSet?
  29. ¿Qué clases de colección son seguras para subprocesos?
  30. ¿Qué son las clases de colección concurrentes?
  31. ¿Qué es BlockingQueue?
  32. ¿Qué es Queue y Stack? Enumere sus diferencias.
  33. ¿Qué es la clase Colecciones?
  34. ¿Qué es la interfaz Comparable y Comparator?
  35. ¿Cuál es la diferencia entre la interfaz Comparable y la interfaz Comparator?
  36. ¿Cómo podemos ordenar una lista de objetos?
  37. Al pasar una colección como argumento a una función, ¿cómo podemos asegurarnos de que la función no podrá modificarla?
  38. ¿Cómo podemos crear una colección sincronizada a partir de una colección dada?
  39. ¿Cuáles son los algoritmos comunes implementados en Collections Framework?
  40. ¿Qué es la notación Big-O? ¿Puedes darme algunos ejemplos?
  41. ¿Cuáles son las mejores prácticas relacionadas con Java Collections Framework?
  42. ¿Qué es Java Priority Queue?
  43. ¿Por qué no podemos escribir código como ListNumber numbers = new ArrayListInteger();?
  44. ¿Por qué no podemos crear una matriz genérica? o escribir código comoListInteger[] array = new ArrayListInteger[10];

Preguntas y respuestas de la entrevista sobre colecciones de Java

  1. ¿Cuáles son las características relacionadas con la colección en Java 8?

    Java 8 ha introducido cambios importantes en la API de recopilación. Algunos de los cambios son:

    1. API de Java Stream para clases de colección que admiten procesamiento secuencial y paralelo
    2. La interfaz iterable se amplía con el método predeterminado forEach() que podemos usar para iterar sobre una colección. Es muy útil cuando se usa con expresiones lambda porque su argumento Consumer es una función interface .
    3. Mejoras en la API de colección miscelánea , como forEachRemaining(Consumer action)métodos en Iteratorla interfaz, Mapa replaceAll(), métodos.compute()merge()
  2. ¿Qué es Java Collections Framework? ¿Cuáles son algunos de los beneficios de Collections Framework?

    Las colecciones se utilizan en todos los lenguajes de programación y la versión inicial de Java contenía algunas clases para colecciones: Vector , Stack , Hashtable y Array . Pero al observar el alcance y el uso más amplios, Java 1.2 presentó el marco de colecciones que agrupa todas las interfaces, implementaciones y algoritmos de colecciones. Las colecciones de Java han recorrido un largo camino con el uso de clases de colecciones genéricas y concurrentes para operaciones seguras para subprocesos. También incluye interfaces de bloqueo y sus implementaciones en el paquete concurrente de Java. Algunos de los beneficios del marco de colecciones son:

    • Esfuerzo de desarrollo reducido al utilizar clases de colección principales en lugar de implementar nuestras propias clases de colección.
    • La calidad del código se mejora con el uso de clases de marco de colecciones bien probadas.
    • Esfuerzo reducido para el mantenimiento del código mediante el uso de clases de colección incluidas con JDK.
    • Reutilización e interoperabilidad
  3. ¿Cuál es el beneficio de los genéricos en Collections Framework?

    Java 1.5 viene con genéricos y todas las interfaces e implementaciones de colección los utilizan de forma intensiva. Los genéricos nos permiten proporcionar el tipo de objeto que puede contener una colección, por lo que si intenta agregar cualquier elemento de otro tipo, se generará un error en tiempo de compilación. Esto evita ClassCastException en tiempo de ejecución porque obtendrá el error en la compilación. Además, los genéricos hacen que el código sea limpio ya que no necesitamos usar el operador de conversión e instanceof . Recomiendo encarecidamente leer el Tutorial de genéricos de Java para comprender mejor los genéricos.

  4. ¿Cuáles son las interfaces básicas de Java Collections Framework?

    Una colección es la raíz de la jerarquía de colecciones. Una colección representa un grupo de objetos conocidos como sus elementos. La plataforma Java no proporciona ninguna implementación directa de esta interfaz. Un conjunto es una colección que no puede contener elementos duplicados. Esta interfaz modela la abstracción matemática de conjuntos y se utiliza para representar conjuntos, como la baraja de cartas. Una lista es una colección ordenada y puede contener elementos duplicados. Puede acceder a cualquier elemento desde su índice. La lista es más como una matriz con longitud dinámica. Un mapa es un objeto que asigna claves a valores. Un mapa no puede contener claves duplicadas: cada clave puede asignarse a un valor como máximo. Algunas otras interfaces son Queue, Dequeue, Iterator, y .SortedSetSortedMapListIterator

  5. ¿Por qué Collection no extiende las interfaces Cloneable y Serializable?

Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don't. A lot of the Collection implementations have a public clone method. However, it doesn't make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation. The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized. So mandating cloning and serialization in all implementations is less flexible and more restrictive. The specific implementation should decide as to whether it can be cloned or serialized.
  1. ¿Por qué la interfaz de Mapa no extiende la interfaz de Colección?

Although Map interface and its implementations are part of the Collections Framework, Map is not collections and collections are not Map. Hence it doesn't make sense for Map to extend Collection or vice versa. If Map extends Collection interface, then where are the elements? The map contains key-value pairs and it provides methods to retrieve the list of Keys or values as Collection but it doesn't fit into the "group of elements" paradigm.
  1. ¿Qué es un iterador?

The Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using _iterator()_ method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements **[Iterator Design Pattern](/community/tutorials/iterator-design-pattern-java "Iterator Design Pattern in Java – Example Tutorial")**.
  1. ¿Cuál es la diferencia entre la interfaz de enumeración y la de iterador?

Enumeration is twice as fast as Iterator and uses very little memory. Enumeration is very basic and fits basic needs. But the Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method names have been improved to make its functionality clear.
  1. ¿Por qué no hay un método como Iterator.add() para agregar elementos a la colección?

The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.
  1. ¿Por qué Iterator no tiene un método para obtener el siguiente elemento directamente sin mover el cursor?

It can be implemented on top of current Iterator interface but since its use will be rare, it doesn't make sense to include it in the interface that everyone has to implement.
  1. ¿Cuál es la diferencia entre Iterator y ListIterator?

-   We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.-   Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.-   ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
  1. ¿Cuáles son las diferentes formas de iterar sobre una lista?

We can iterate over a list in two different ways - using iterator and using for-each loop.```ListString strList = new ArrayList();//using for-each loopfor(String obj : strList){    System.out.println(obj);}//using iteratorIteratorString it = strList.iterator();while(it.hasNext()){    String obj = it.next();    System.out.println(obj);}```Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw `ConcurrentModificationException`.
  1. ¿Qué entiendes por propiedad de falla rápida del iterador?

Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws `ConcurrentModificationException`. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
  1. ¿Cuál es la diferencia entre fail-fast y fail-safe?

Iterator fail-safe property work with the clone of underlying collection, hence it's not affected by any modification in the collection. By design, all the collection classes in `java.util` package are fail-fast whereas collection classes in `java.util.concurrent` are fail-safe. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException. Check this post for [CopyOnWriteArrayList Example](/community/tutorials/copyonwritearraylist-java).
  1. ¿Cómo evitar ConcurrentModificationException al iterar una colección?

We can use concurrent collection classes to avoid `ConcurrentModificationException` while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList. Check this post for [ConcurrentHashMap Example](/community/tutorials/concurrenthashmap-in-java).
  1. ¿Por qué no hay implementaciones concretas de la interfaz Iterator?

Iterator interface declare methods for iterating a collection but its implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has its own Iterator implementation nested class. This allows collection classes to chose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.
  1. ¿Qué es UnsupportedOperationException?

`UnsupportedOperationException` is the exception used to indicate that the operation is not supported. It's used extensively in [JDK](/community/tutorials/difference-jdk-vs-jre-vs-jvm "Difference between JDK, JRE and JVM in Java") classes, in collections framework `java.util.Collections.UnmodifiableCollection` throws this exception for all `add` and `remove` operations.
  1. ¿Cómo funciona HashMap en Java?

HashMap stores key-value pair in `Map.Entry` static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in `put` and `get` methods. When we call `put` method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there is an already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and stores this key-value Entry. When we call `get` method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return its value. The below image will explain these detail clearly. [![java-hashmap-entry-impl](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/01/java-hashmap-entry-impl-450x245.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/01/java-hashmap-entry-impl.png) The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is **16** and load factor is 0.75. The threshold is capacity multiplied by load factor and whenever we try to add an entry if map size is greater than the threshold, HashMap rehashes the contents of the map into a new array with a larger capacity. The capacity is always the power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from the database, it's a good idea to initialize the HashMap with correct capacity and load factor.
  1. ¿Cuál es la importancia de los métodos hashCode() y equals()?

HashMap uses the Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key's might produce the same hashCode() and equals() output and in that case, rather than storing it at a different location, HashMap will consider the same and overwrite them. Similarly all the collection classes that doesn't store duplicate data use hashCode() and equals() to find duplicates, so it's very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.-   If `o1.equals(o2)`, then `o1.hashCode() == o2.hashCode()`should always be `true`.-   If `o1.hashCode() == o2.hashCode` is true, it doesn't mean that `o1.equals(o2)` will be `true`.
  1. ¿Podemos utilizar cualquier clase como clave de mapa?

We can use any class as Map Key, however following points should be considered before using them.-   If the class overrides equals() method, it should also override hashCode() method.-   The class should follow the rules associated with equals() and hashCode() for all instances. Please refer earlier question for these rules.-   If a class field is not used in equals(), you should not use it in hashCode() method.-   Best practice for user defined key class is to make it immutable, so that hashCode() value can be cached for fast performance. Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability. For example, let's say I have a class `MyKey` that I am using for the HashMap key.        ```    //MyKey name argument passed is used for equals() and hashCode()    MyKey key = new MyKey("Pankaj"); //assume hashCode=1234    myHashMap.put(key, "Value");        // Below code will change the key hashCode() and equals()    // but its location is not changed.    key.setName("Amit"); //assume new hashCode=7890        //below will return null because HashMap will try to look for key    //in the same index as it was stored but since the key is mutated,     //there will be no match and it will return null.    myHashMap.get(new MyKey("Pankaj"));     ```        This is the reason why String and Integer are mostly used as HashMap keys.
  1. ¿Cuáles son las diferentes vistas de colección que ofrece la interfaz de Mapa?

Map interface provides three collection views:1.  **SetK keySet()**: Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.2.  **CollectionV values()**: Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.3.  **SetMap.EntryK, V entrySet()**: Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's remove operation, or the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
  1. ¿Cuál es la diferencia entre HashMap y Hashtable?

HashMap and Hashtable both implements Map interface and looks similar, however, there is the following difference between HashMap and Hashtable.1.  HashMap allows null key and values whereas Hashtable doesn't allow null key and values.2.  Hashtable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, Hashtable is suitable for multi-threaded environment.3.  `LinkedHashMap` was introduced in Java 1.4 as a subclass of HashMap, so incase you want iteration order, you can easily switch from HashMap to LinkedHashMap but that is not the case with Hashtable whose iteration order is unpredictable.4.  HashMap provides Set of keys to iterate and hence it's fail-fast but Hashtable provides Enumeration of keys that doesn't support this feature.5.  Hashtable is considered to be legacy class and if you are looking for modifications of Map while iterating, you should use ConcurrentHashMap.
  1. ¿Cómo decidir entre HashMap y TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
  1. ¿Cuáles son las similitudes y diferencias entre ArrayList y Vector?

ArrayList and Vector are similar classes in many ways.1.  Both are index based and backed up by an array internally.2.  Both maintains the order of insertion and we can get the elements in the order of insertion.3.  The iterator implementations of ArrayList and Vector both are fail-fast by design.4.  ArrayList and Vector both allows null values and random access to element using index number.These are the differences between ArrayList and Vector.1.  Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList.2.  ArrayList is faster than Vector because it doesn't have any overhead because of synchronization.3.  ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class.
  1. ¿Cuál es la diferencia entre Array y ArrayList? ¿Cuándo se debe utilizar Array en lugar de ArrayList?

Arrays can contain primitive or Objects whereas ArrayList can contain only Objects. Arrays are fixed-size whereas ArrayList size is dynamic. Arrays don't provide a lot of features like ArrayList, such as addAll, removeAll, iterator, etc. Although ArrayList is the obvious choice when we work on the list, there are a few times when an array is good to use.-   If the size of list is fixed and mostly used to store and traverse them.-   For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types.-   If you are working on fixed multi-dimensional situation, using [][] is far more easier than ListList
  1. ¿Cuál es la diferencia entre ArrayList y LinkedList?

ArrayList and LinkedList both implement List interface but there are some differences between them.1.  ArrayList is an index based data structure backed by Array, so it provides random access to its elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to its previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList.2.  Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle.3.  LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.
  1. ¿Qué clases de colección proporcionan acceso aleatorio a sus elementos?

ArrayList, HashMap, TreeMap, Hashtable, and Vector classes provide random access to its elements. Download [java collections pdf](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/01/java-collections-framework.pdf) for more information.
  1. ¿Qué es EnumSet?

`java.util.EnumSet` is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s). Check this post for [java enum tutorial](/community/tutorials/java-enum).
  1. ¿Qué clases de colección son seguras para subprocesos?

Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment. Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the clone of the collection, so they are safe to use in multi-threaded environment.
  1. ¿Qué son las clases de colección concurrentes?

Java 1.5 Concurrent package (`java.util.concurrent`) contains thread-safe collection classes that allow collections to be modified while iterating. By design Iterator implementation in `java.util` packages are fail-fast and throws ConcurrentModificationException. But Iterator implementation in `java.util.concurrent` packages are fail-safe and we can modify the collection while iterating. Some of these classes are `CopyOnWriteArrayList`, `ConcurrentHashMap`, `CopyOnWriteArraySet`.Read these posts to learn about them in more detail.-   [Avoid ConcurrentModificationException](/community/tutorials/java-util-concurrentmodificationexception)-   [CopyOnWriteArrayList Example](/community/tutorials/copyonwritearraylist-java)-   [HashMap vs ConcurrentHashMap](/community/tutorials/concurrenthashmap-in-java)
  1. ¿Qué es BlockingQueue?

`java.util.concurrent.BlockingQueue` is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element. BlockingQueue interface is part of the java collections framework and it’s primarily used for implementing the producer-consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumers in BlockingQueue as it’s handled by implementation classes of BlockingQueue. Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, etc. Check this post for use of BlockingQueue for [producer-consumer problem](/community/tutorials/java-blockingqueue-example).
  1. ¿Qué es Queue y Stack? Enumere sus diferencias.

Both Queue and Stack are used to store data before processing them. `java.util.Queue` is an interface whose implementation classes are present in java concurrent package. Queue allows retrieval of element in First-In-First-Out (FIFO) order but it's not always the case. There is also Deque interface that allows elements to be retrieved from both end of the queue. The stack is similar to queue except that it allows elements to be retrieved in Last-In-First-Out (LIFO) order. Stack is a class that extends Vector whereas Queue is an interface.
  1. ¿Qué es la clase Colecciones?

`java.util.Collections` is a utility class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends. This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse, etc.
  1. ¿Qué es la interfaz Comparable y Comparator?

Java provides a Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. The comparable interface has a compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as an argument. But, in most real-life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on age. This is the situation where we need to use `Comparator` interface because `Comparable.compareTo(Object o)` method implementation can sort based on one field only and we can’t choose the field on which we want to sort the Object. Comparator interface `compare(Object o1, Object o2)` method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if the first argument is less than the second one and returns zero if they are equal and positive int if the first argument is greater than the second one. Check this post for use of Comparable and Comparator interface to [sort objects](/community/tutorials/comparable-and-comparator-in-java-example).
  1. ¿Cuál es la diferencia entre la interfaz Comparable y la interfaz Comparator?

Comparable and Comparator interfaces are used to sort collection or array of objects. Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic. Comparator interface is used to provide different algorithms for sorting and we can choose the comparator we want to use to sort the given collection of objects.
  1. ¿Cómo podemos ordenar una lista de objetos?

If we need to sort an array of Objects, we can use `Arrays.sort()`. If we need to sort a list of objects, we can use `Collections.sort()`. Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator). Collections internally uses Arrays sorting method, so both of them have same performance except that Co
SUSCRÍBETE A NUESTRO BOLETÍN 
No te pierdas de nuestro contenido ni de ninguna de nuestras guías para que puedas avanzar en los juegos que más te gustan.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Scroll al inicio