Try this:
import java.util.LinkedHashSet;
import java.util.Set;
public class Party {
private final Set<String> players;
public Party() {
this.players = new LinkedHashSet<>();
}
public void toggle(String player) {
if (players.contains(player)) {
players.remove(player);
} else {
players.add(player);
}
}
public String[] toArray() {
return players.toArray(new String[players.size()]);
}
public Set<String> toSet() {
return new LinkedHashSet<>(players);
}
}
Here's an example / test of how to use the Party
class:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Party p = new Party();
p.toggle("Pedro"); // Adiciona o Pedro
System.out.println(Arrays.asList(p.toArray())); // Imprime [Pedro]
p.toggle("Maria"); // Adiciona a Maria
System.out.println(Arrays.asList(p.toArray())); // Imprime [Pedro, Maria]
p.toggle("Pedro"); // Remove o Pedro
System.out.println(Arrays.asList(p.toArray())); // Imprime [Maria]
p.toggle("Carlos"); // Adiciona o Carlos
p.toggle("Fernando"); // Adiciona o Fernando
System.out.println(p.toSet()); // Imprime [Maria, Carlos, Fernando]
p.toggle("Carlos"); // Remove o Carlos
System.out.println(p.toSet()); // Imprime [Maria, Fernando]
}
}
See rolling in ideone
Note that you add / remove the players with the toggle(String)
method. To get the list of players as an array . use the toArray()
method. If you prefer to work with the players list in the form of a Set
, use the toSet()
method. In testing, I use both to show how they can be used.
Modifying the array returned by toArray()
will not interfere with Party
, and changing Party
will not interfere with arrays previously obtained through toArray()
. Likewise, modifying Set
returned by toSet()
does not interfere with Party
and changing Party
does not interfere with Set
s previously obtained by toSet()
. This ensures that changes in Party
do not cause unanticipated side effects in arrays and Set
s previously obtained, and also ensures that changes in these arrays and Set
s do not cause unanticipated side effects in Party
.
In addition, it should be noted that players will always be kept in the order they were entered. This is because we are using LinkedHashSet
. If instead a HashSet
was used, the order of the players would be random. If a TreeSet
was used, the players would be automatically sorted alphabetically.
I'm also assuming that Party
will be used in a single thread . If this is not the case, the simplest way to make it safe to be used in multiple threads is to place the synchronized
modifier in methods toggle(String)
, toArray()
and toSet()
.