r/javahelp • u/[deleted] • Feb 25 '20
How do I modify a character array in place?
I am trying to replace the characters in an array with their frequency.
For example, ['a', 'a', 'b'] should become ['a', '2', 'b', '1'].
I'm finding this quite difficult to do, since Java arrays cannot shrink or expand at runtime and this needs to be done in-place, without extra space.
4
u/darksounds Extreme Brewer Feb 25 '20
I pointed it out in a reply below, but I'm going to post it here so it can be more easily found.
You're not actually trying to replace the characters with their frequency, you're trying to compress the array, as per this leetcode problem.
['a', 'a', 'b'] should become ['a', '2', 'b'] so as to fit inside the original array.
Take a look at example 3 to understand this a little better.
1
6
u/PhantomOTOpera Feb 25 '20
You're correct. Arrays are not dynamic (they can't change size). If you need more space, you should create a new array with a bigger size each time you want to add a new element and then add the new element to the larger array.
1
Feb 25 '20
Could you explain 'creating a new array each time' ? How would I modify the original array using this new one?
7
u/PhantomOTOpera Feb 25 '20
You can't modify the original array. Once you create an array in java its permanent (in terms of size, the contents may still change). Creating a new array works just like you would create the first array
char[] x = new char[4]; // or whatever size you need
5
u/96dpi Feb 25 '20
You may want to use an ArrayList instead. You can change the size of an ArrayList.