Extending arrays
final String[] member = {"Eve", "John", "Peter", "Jill"};
final String newCourseMember = "Ernest";
member.length = 5; // Error: Size unchangeable
member[4] = newCourseMember;
public static void main(String[] args) {
❶ String[] member = {"Eve", "John", "Peter", "Jill"};
final String newMember = "Ernest";
member ❷= append(member, newMember);
}
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[copy.length - 1] = 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. |
final String[] member = {"Eve", "John", "Peter", "Jill"}; System.out.println("Original array: " + Arrays.toString(member)); final String newMember = "Ernest"; member = append(member, newMember); System.out.println("Extended array: " + Arrays.toString(member));
Original array: [Eve, John, Peter, Jill]
Extended array: [Eve, John, Peter, Jill, Ernest]
Arrays.copyOf()
public static void main(String[] args) { final int [] start = {1,7,-4}, added = append(start, 77); System.out.println("added: " + Arrays.toString(added)); } 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. 145
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. 146
Purge 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:
|