Let’s get issue simple. We don’t need to delete duplicate character. We just remove the charachter at index 2. The string is “abcde”.
StringBuilder sb = new StringBuilder("abcde");
char one = sb.charAt(2); // comment1, we know it's 'c'
sb = sb.deleteCharAt(2); // comment2, let's delete 'c'. What would "abcde" be?
// It's so ugly to be "ab de", so designer makes it be "abde"
char two = sb.charAt(2); // comment3, now you will know the result ^v^
For comment2, how does it make “abcde” to “abde”? Let’s look into source of StringBuilder. StringBuilder is a subClass of AbstractStringBuilder. And deleteCharAt(int index) is implemented in AbstractStringBuilder.
public AbstractStringBuilder deleteCharAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
System.arraycopy(value, index+1, value, index, count-index-1);
count--;
return this;
}
Let’s omite index validation. What does System.arraycopy(value, index+1, value, index, count-index-1);
do? You can find it’s doc here.
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
Copies an array from the specified source array (which is “abcde”), beginning at the
specified position (index+1
, which is 3), to the specified position (index
, which is 2) of the destination
array (which is “abcde” too). A subsequence of array components are copied from the source
array referenced bysrc
to the destination array referenced bydest
(src
anddest
are the same here, “abcde”).
The number of components copied is equal to thelength
argument (length
here is 5-2-1, it’s 2. So it will copy 2 chars). The
components at positionssrcPos
throughsrcPos+length-1
in the source
array are copied into positionsdestPos
throughdestPos+length-1
(srcPos
here is 2+1, it’s 3.srcPos+length-1
is 3+2-1, it’s 4),
respectively, of the destination array.
So System.arraycopy(value, index+1, value, index, count-index-1);
means copy 2 chars from index 3, to override index 2, override from index 2 to 3. Copy ‘de’ to override ‘cd’. So after System.arraycopy(value, index+1, value, index, count-index-1);
, makes sb.value
to be “abdee”(Delete ‘l’ already.). then count–, means “abdee” remove last char, so it becomes “abde”.
will the next "l" takes position of the previous one after deleting it?
Yes, it will.
See? Coding is not so hard and not so mystic. And the direct way is code yourself and run it.
solved Duplicates Reduction