6
When I store something inside a Set
, the order in which it stores is random?
And how could I order a set Set
?
6
When I store something inside a Set
, the order in which it stores is random?
And how could I order a set Set
?
6
The Set
is just an interface. The order depends on the implementation.
The HashSet
has no guarantee of any order. In practice it is random.
The LinkedHashSet
maintains the order in which the elements are inserted.
The TreeSet
sorts the elements according to the natural ordering (crescent, alphabetical, etc). It is possible to pass a Comparator
in the constructor to specify how it should order if the natural ordering does not exist or is not the desired one.
To instantiate the TreeSet
with a Comparator
, we can use a separate class, an anonymous class or a reference to a method (java 8):
Classy:
public void instanciaElemento() {
TreeSet<SuaClasse> = new TreeSet<>(new MeuComparator());
}
public static class MeuComparator implements Comparator<SuaClasse> {
@Override
public int compare(SuaClasse a, SuaClasse b) {
// Implementação...
// Retorna 1 se a é depois de b, -1 se a é antes de b ou 0 se os dois são iguais.
}
}
Anonymous class:
public void instanciaElemento() {
TreeSet<SuaClasse> = new TreeSet<>(new Comparator<> {
@Override
public int compare(SuaClasse a, SuaClasse b) {
// Implementação...
// Retorna 1 se a é depois de b, -1 se a é antes de b ou 0 se os dois são iguais.
}
});
}
With reference to method:
public void instanciaElemento() {
TreeSet<SuaClasse> = new TreeSet<>(EstaClasse::metodoComparador);
}
private static int metodoComparador(SuaClasse a, SuaClasse b) {
// Implementação...
// Retorna 1 se a é depois de b, -1 se a é antes de b ou 0 se os dois são iguais.
}
6
Although TreeSet
sort the elements, the decision to use this implementation should not be made just in case you need to sort the list at a time.
By instantiating a TreeSet
, HashSet
or LinkedHashSet
you should consider the advantages of each, especially with regard to the cost to add and the cost to recover an element. Some implementations work best to add various elements, others to recover elements and all this depends on the variety of objects placed inside.
If you simply have a set and want to generate an ordered list, just use the ArrayList
who receives a Collection
whichever.
Thus:
Set<String> conjunto = new HashSet<>();
conjunto.add("Jose");
conjunto.add("Maria");
conjunto.add("Joao");
conjunto.add("Maria");
System.out.println(conjunto);
//conjunto -> lista
List<String> lista = new ArrayList<>(conjunto);
Collections.sort(lista);
System.out.println(lista);
4
To complete the @Victor response
The set
by itself does not hold anything, since it is a Interface
:
Article on set
here
Imagery:
In what order is a Set stored? Random?
Yes
Example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hset =
new HashSet<String>();
// Adding elements to the HashSet
hset.add("Apple");
hset.add("Mango");
hset.add("Grapes");
hset.add("Orange");
hset.add("Fig");
//Addition of duplicate elements
hset.add("Apple");
hset.add("Mango");
//Addition of null values
hset.add(null);
hset.add(null);
//Displaying HashSet elements
System.out.println(hset);
}
}
Output:
[null, Mango, Grapes, Apple, Orange, Fig]
If in case you intend to make one Set
of some object created by you, you must implement Comparable
:
For example this for an account class:
public class Conta implements Comparable<Conta> {
private int numero;
private String titular;
// outros metodos e atributos
@Override
public int compareTo(Conta outraConta) {
if (this.numero < outraConta.numero) {
return -1;
}
if (this.numero > outraConta.numero) {
return 1;
}
return 0;
}
}
You got a good article here
I implemented Comparable in a class and put several objects of this class in a Hashset, but when printing the list it was not sorted. What I did wrong? :/
@Math You are in the place indicated to publish your doubt along with the code properly indented ;) assuming that it must be a kind of joke/test and entering the same :)... There are several reasons maybe your comparable is poorly implemented, or the answer I think you want is forgot to implement the equals and hashcode? (I’m right or nothing to do?)
The truth is that Hashset is random, whether or not you implement Comparable makes no difference to this class. Who uses Comparable (and Comparator) is actually Treeset. See: It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
on the link: Hashset - Java SE7. Changing the Hashset code to Treeset it now displays the objects in an orderly manner defined by the method compareTo()
. Tendeus? ;-)
pufff yes, I am very grateful for this explanation, as you noticed I was really convinced it was possible ;) and I thought I had "caught you" in the previous answer, it was more like hitting a wall with real resolution :Thanks again @Math
Browser other questions tagged java classification set hashset
You are not signed in. Login or sign up in order to post.
Here’s an overview of the different types of Java collections: What types of collections and their differences in java?
– Math
Related (to C#): http://answall.com/questions/29226/cria-lista-sem-values-duplicated
– Maniero
Related: https://answall.com/q/307385/64969
– Jefferson Quesado