Cristopher Ontiveros
Cristopher Ontiveros

Reputation: 36

Array to Set not cuts off java array

I am converting an arraylist to a set in java and the resulting set is not producing the expected results.

    String[] characterName = {"C","A","P","T","A","I","N","A","M","E","R","I","C","A"};
    String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    List<String> pool = new ArrayList<String>();

    for(int i=0;i<characterName.length;i++) {
        pool.add(characterName[i]);
    }

    int difference = 19-characterName.length;

    for(int i=0;i<difference;i++) {
        pool.add(alphabet[i]);
    }

    Collections.shuffle(pool);
    Set<String> poolSet= new HashSet<>();
    poolSet.addAll(pool);

I have debugged this but when I addAll from pool to the hashset, it only adds the first 11 characters of the array. EVEN though when I debug, it says pool = 19, it only adds 11. Am I calling this wrong? It seems so simple, but it's not adding all. Any input is greatly appreciated.

Upvotes: 0

Views: 57

Answers (1)

Tyler Lee
Tyler Lee

Reputation: 2785

Sets in java either contain an item or they don't. They don't contain multiple copies of it.

In your example, out of CAPTAINAMERICAABCDE, there is only 11 unique characters, CAPTINMERBD. That's why you end up with 11 in the end.

You will likely want to use a List instead, as that would allow multiple instances of the same thing.

Upvotes: 1

Related Questions