Extending arrays
final String[] member = {"Eve", "John", "Peter", "Jill"};
member.length = 5; // Error: Size unchangeable
member[4] = "Ernest";| Code | String[] member = {"Eve", "John", "Peter", "Jill"}; { String[] memberCopy = new String[member.length + 1]; for (int i = 0; i < member.length; i++) { memberCopy[i] = member[i]; } memberCopy[member.length] = "Ernest"; member = memberCopy; // Switching to new array, releasing old } IO.println(Arrays.toString(member)); |
|---|---|
| Result | [Eve, John, Peter, Jill, Ernest] |
void main() {
❶ String[] member = {"Eve", "John", "Peter", "Jill"};
member ❷= append(member, "Ernest");
}
static String[] append (final String[] values, final String newValue) {
final String[] copy = ❸ new String[values.length + 1];
for (int i = 0; i < values.length; i++) { ❹
copy[i] = values[i]; ❺
}
copy[values.length] = newValue; ❻
return copy;
}|
No final here: Reference will be re-assigned. |
|
|
Assigning reference to enlarged array. |
|
|
Creating an empty array capable of holding one more value. |
|
|
Looping over existing values. |
|
|
Assigning old values one by one to corresponding index positions. |
|
|
Assigning new value to last index position before returning newly created array's reference. |
| Code | final String[] member = {"Eve", "John", "Peter", "Jill"}; IO.println("Original array: " + Arrays.toString(member)); member = append(member, "Ernest"); IO.println("Extended array: " + Arrays.toString(member)); |
|---|---|
| Result | Original array: [Eve, John, Peter, Jill] Extended array: [Eve, John, Peter, Jill, Ernest] |
Arrays.copyOf() | Code | void main() {
final int [] start = {1, 7, -4},
start = append(start, 77);
IO.println("added: " + Arrays.toString(start));
}
static public int[] append(final int[] values, final int newValue) {
final int[] result = Arrays.copyOf(values, values.length + 1);
result[values.length] = newValue;
return result;} |
|---|---|
| Result | added: [1, 7, -4, 77] |
No. 151
Implementing append directly
|
Q: |
We reconsider our Change the implementation. Do not use methods from
|
|
A: |
/**
* <p>Create a new array consisting of given array values and new value at its end. Example:</p>
*
* <p>Given Array {1, 3, 0} and new value 77 results in {1, 3, 0, 77}. </p>
*
* @param values Given values
* @param newValue Value to be appended
* @return A new array prepending the input array values to the new value .
*/
static public int[] append(final int[] values, final int newValue) {
final int[] result = new int[values.length + 1]; ❶
for (int i = 0; i < values.length; i++) { ❷
result[i] = values[i];
}
result[values.length] = newValue; ❸
return result;
}
|
No. 152
Purging duplicates
|
Q: |
Consider the following This array contains duplicates to be purged leaving us with a sorted result containing distinct values: Implement a corresponding
Use (at least) these unit tests: TipYou may follow these steps:
|
|
A: |
Following the steps outlined in the hints we may: |
