Try it like 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 is an example/test of how to use the class Party
:
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]
}
}
Watch it run on ideone
Note that you add/remove players with the method toggle(String)
. To get the list of players as a array. use the method toArray()
. If you prefer to work with the list of players in the form of a Set
, use the method toSet()
. In the test, I use both in order to show how they can be used.
Modify the array returned by toArray()
will not interfere with Party
, and change the Party
will not interfere with arrays previously obtained through the toArray()
. Likewise, modify the Set
returned by toSet()
does not interfere with Party
and change the Party
does not interfere with us Set
s previously obtained by toSet()
. This ensures that changes in Party
do not cause unforeseen side effects on arrays and Set
previously obtained, and also ensures that changes in these arrays and Set
do not cause unforeseen side effects on Party
.
In addition, it should be noted that the players will always be kept in the order in which they were entered. This is because we are using a LinkedHashSet
. If instead a HashSet
, the order of players would be random. If a TreeSet
, the players would be automatically ordered alphabetically.
I’m also assuming that the Party
will be used in a single thread. If this is not the case, the simplest way to make it safe to use in multiple threads is to put the modifier synchronized
in the methods toggle(String)
, toArray()
and toSet()
.
Why didn’t you get
ArrayList
?– Jéf Bueno
Why every player you type
/party PLAYER
needs aArrayList
new.– Lucas Caresia
Edit the question with the code you already have, I think I misunderstood the question.
– Jéf Bueno
But like this, you want to wear one
"lista"
to store/add/remove players, right?– Jéf Bueno
I want a
String[] party
that you can useparty.add(PLAYER);
– Lucas Caresia