0

I am doing one exercise in Absolute Java.
The Question is: Write a static method that has a partially filled array of characters as a formal parameter and that deletes all repeated letters from the array. The method should have two formal parameters: an array parameter and a formal parameter of type int that gives the number of array positions used. When the letter is deleted, the remaining letters are moved one position to fill in the gap.

What I think of is using hashset, it should be the most easiest way.
And another way that I am thinking is converting array to list , deleting the duplicates element and then transfer it back.
Here is a problem for me: how to write that code?? (why I am asking it?)

public static char[] deleteRepeats(char[] array, int size)
{
    ArrayList<String> newarray = new ArrayList<String>();
    newarray = Arrays.asList(array);
}

it says type mismatching, how can I correct the code?

Another question is: Back to the initial question, how to use partially filled array to implement it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Justin
  • 2,765
  • 6
  • 24
  • 25

1 Answers1

1
ArrayList<String> newarray = new ArrayList<String>();

Is an array list of Generic type String. However your parameters are of char type. Therefore they are not interchangeable. That's whats throwing the Type Mismatch error.

You are right using a Set is the easiest way to implement it. However I don't know whether the exercise wants you to manually do the work.

However you if you cannot use the wrapper class Character and must use the char type then you must do manual conversion if you are going to get a Set to do your replacement work for you.

EDIT:

You cannot use Arrays.asList() method to get a list like that. That method takes java objects as arguments not primitive types. And when you pass the char[] the only object it sees is the array itself.

So the result is a List<char[]> since generics do not support primitive types.

Thihara
  • 7,031
  • 2
  • 29
  • 56
  • thanks, after changing the method signature to deleteRepeats(Character[] array, int size), the problem is resolved – Justin Dec 10 '12 at 05:14
  • 1
    OK. But you should consider doing it the manual way since I think that's what the exercise was about... – Thihara Dec 10 '12 at 05:15