208k views
5 votes
Write a static method removeDuplicates(Character[] in) that returns a new array of the characters in the given array, but without any duplicate characters. Always keep the first copy of the character and remove the subsequent ones. For example, if in contains b, d, a, b, f, a, g, a, a, f, the method should return an array b, d, b, f, g.

1 Answer

3 votes

Final answer:

To remove duplicate characters from an array, you can compare each element with the rest of the elements and skip duplicates. Here is an example implementation.

Step-by-step explanation:

To write a static method that removes duplicate characters from an array, you can create a new array and compare each element with the rest of the elements in the original array. If a duplicate is found, skip it and move on to the next element.

Here is an example implementation:

public static Character[] removeDuplicates(Character[] in) {
List<Character> newList = new ArrayList<>();
for (int i = 0; i < in.length; i++) {
boolean isDuplicate = false;
for (int j = 0; j < i; j++) {
if (in[i].equals(in[j])) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newList.add(in[i]);
}
}
Character[] newArray = new Character[newList.size()];
return newList.toArray(newArray);
}

User Zakdances
by
7.9k points