Avoid duplicates without sets?

I am in a beginner Java class and I haven't gotten the chance to learn how to avoid duplicated values when storing values inside arrays.

String[] newAlphabet = new String[26];

for(int I = 0; I < newAlphabet.length; I++){

 int random = (65 + (int)(Math.random() * ((90 - 65) + 1));
 char ascii = (char)random;
 String letters = ascii + "";

if(letters != newAlphabet[0] && letters != newAlphabet[1] ... so on and so on until
                                                               newAlphabet[25])
     newAlphabet[I] = letters;
}//end

So this is my pseudo code for part of my program and the point of it is to avoid having duplicated letters inside the array.

The problem that I am having is inside the if statement. Instead of typing letters != newAlphabet[] to 25, is there another way of doing it?

I have seen some of the forums in stackedoverflow that I should use HashSet but I have not learned that? I can ask my teacher if I am allowed but is there another way to avoid this problem?

I have been thinking of using for-each loop to search through all the elements in the array but I haven't thought out the plan long enough if it's valid.


As you are talking about a beginner Java class, I am assuming you are fairly new to programming. So, rather than just give you a library function that will do it for you, let's walk through the steps of how to do this with just the basic code so you can get a better idea of what is going on behind the scenes.

Firstly, for any repetitive action, think loops. You want to check, for each letter in your new alphabet, if the one you are about to add matches it. So...

boolean exists = false; //indicates whether we have found a match
for (int j = 0; j < 26; j++) { //for each letter in the new alphabet
    //true if this one, or a previous one is a match
    exists = exists || letters == newAlphabet[i];
}
//if we don't have a match, add the new letter
if (!exists) newAlphabet[I] = letters;

Now, as you are building up your new alphabet as we go, we don't have a full 26 letters for most cases of running this code, so only check the parts of the new alphabet we have defined:

boolean exists = false;
for (int j = 0; j < I; j++) { //note in this line we stop before the insertion point
    exists = exists || letters == newAlphabet[i];
}
if (!exists) newAlphabet[I] = letters;

Finally, we don't need to keep checking if we have already found a match, so we can change the loop to stop when we have found a match:

boolean exists = false;
int j = 0;
while (!exists && j < I) { //we now also stop if we have already found a match
    exists = letters == newAlphabet[i];
    //as we are stopping at the first match,
    //we no longer need to allow for previous matches
}
if (!exists) newAlphabet[I] = letters;