X Tutup
Skip to content

Commit abed8fc

Browse files
committed
array tampering. still not sure it is right.
1 parent 895f065 commit abed8fc

File tree

2 files changed

+147
-0
lines changed

2 files changed

+147
-0
lines changed

IntroAndWorkBook/arrays.adoc

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,117 @@ donuts[2] = "powdered"; // -> ["chocolate", "glazed", "powdered", "strawberry"
120120
System.out.println(donuts[2]); // powdered
121121
----
122122

123+
=== Array Size Limitations: A Java Reality
124+
125+
One of the most important things to understand about arrays in Java is that **once you create an array, its size is fixed**. You cannot make an array larger or smaller after it's been created. This is different from some other programming languages, but it's a fundamental characteristic of how Java manages memory.
126+
127+
[source]
128+
----
129+
// This creates an array of exactly 5 elements
130+
int[] scores = new int[5];
131+
132+
// You CANNOT do this - it would cause a compilation error:
133+
// scores = new int[10]; // This doesn't resize the array!
134+
----
135+
136+
==== Why Arrays Have Fixed Sizes
137+
138+
Java arrays have fixed sizes for several important reasons:
139+
140+
1. **Memory Efficiency**: Java knows exactly how much memory to allocate when the array is created
141+
2. **Performance**: Fixed-size arrays allow for very fast access to elements using simple math
142+
3. **Type Safety**: Java can guarantee that all elements are the same type and fit in the allocated space
143+
4. **Predictable Behavior**: Your program won't unexpectedly run out of memory due to arrays growing
144+
145+
==== When You Need a Bigger Array
146+
147+
If you need more space in your array, you have to create a new, larger array and copy the elements from the old one:
148+
149+
[source]
150+
----
151+
// Original array with 3 elements
152+
String[] donuts = {"chocolate", "glazed", "jelly"};
153+
154+
// We want to add more donuts, so we need a bigger array
155+
String[] biggerDonuts = new String[5];
156+
157+
// Copy the old donuts to the new array
158+
for (int i = 0; i < donuts.length; i++) {
159+
biggerDonuts[i] = donuts[i];
160+
}
161+
162+
// Now we can add new donuts
163+
biggerDonuts[3] = "powdered";
164+
biggerDonuts[4] = "strawberry";
165+
166+
// The original 'donuts' array still exists, but we're using 'biggerDonuts' now
167+
----
168+
169+
==== Java's Garbage Collection Makes This Manageable
170+
171+
You might think, "Isn't creating new arrays and copying wasteful?" In many programming languages, this would be a serious concern. But Java has a **garbage collector** that automatically manages memory for you.
172+
173+
Here's what happens behind the scenes:
174+
175+
1. **You create a new, larger array**: Java allocates the needed memory
176+
2. **You copy elements from old to new**: This happens quickly - Java is optimized for array operations
177+
3. **You stop using the old array**: When no variables point to the old array anymore
178+
4. **Garbage collector cleans up**: Java automatically reclaims the memory from the old array
179+
180+
[source]
181+
----
182+
// Step 1: Original array
183+
int[] smallArray = {1, 2, 3};
184+
185+
// Step 2: Create bigger array and copy (this is fine!)
186+
int[] bigArray = new int[6];
187+
for (int i = 0; i < smallArray.length; i++) {
188+
bigArray[i] = smallArray[i];
189+
}
190+
191+
// Step 3: Use the new array
192+
smallArray = null; // We're done with the small array
193+
194+
// Step 4: Garbage collector will eventually clean up the old array automatically
195+
// You don't need to do anything!
196+
----
197+
198+
==== The Java Philosophy: Predictable and Safe
199+
200+
This design reflects Java's philosophy of being **predictable** and **safe**:
201+
202+
- **Predictable**: You always know exactly how big your arrays are
203+
- **Safe**: You can't accidentally access memory that doesn't belong to your array
204+
- **Managed**: The garbage collector handles memory cleanup automatically
205+
206+
For dynamic-sized collections, Java provides `ArrayList`, `LinkedList`, and other collection classes that handle the "create bigger array and copy" process automatically. But understanding arrays helps you appreciate how those more advanced collections work under the hood.
207+
208+
==== Try This in jshell
209+
210+
[source]
211+
----
212+
jshell> int[] original = {10, 20, 30};
213+
original ==> int[3] { 10, 20, 30 }
214+
215+
jshell> int[] expanded = new int[5];
216+
expanded ==> int[5] { 0, 0, 0, 0, 0 }
217+
218+
jshell> for (int i = 0; i < original.length; i++) {
219+
...> expanded[i] = original[i];
220+
...> }
221+
222+
jshell> expanded[3] = 40;
223+
expanded[3] ==> 40
224+
225+
jshell> expanded[4] = 50;
226+
expanded[4] ==> 50
227+
228+
jshell> System.out.println(Arrays.toString(expanded));
229+
[10, 20, 30, 40, 50]
230+
----
231+
232+
Remember: creating new arrays and copying isn't a "bad thing" in Java - it's just how the language works. The garbage collector makes this approach practical and efficient.
233+
123234
=== Chapter Exercises
124235

125236
Try these exercises in jshell to practice working with arrays:
@@ -224,3 +335,39 @@ for (String fruit : fruits) {
224335
}
225336
System.out.println("Fruits starting with vowels: " + vowelCount);
226337
```
338+
339+
*Exercise 5: Array Resizing Practice*
340+
341+
Practice creating larger arrays and copying data:
342+
```
343+
// Start with a small array
344+
int[] originalGrades = {85, 92, 78};
345+
System.out.println("Original array length: " + originalGrades.length);
346+
System.out.println("Original grades: " + Arrays.toString(originalGrades));
347+
348+
// Create a larger array to hold more grades
349+
int[] expandedGrades = new int[6];
350+
351+
// Copy existing grades to the new array
352+
for (int i = 0; i < originalGrades.length; i++) {
353+
expandedGrades[i] = originalGrades[i];
354+
}
355+
356+
// Add new grades
357+
expandedGrades[3] = 95;
358+
expandedGrades[4] = 88;
359+
expandedGrades[5] = 91;
360+
361+
System.out.println("Expanded array length: " + expandedGrades.length);
362+
System.out.println("All grades: " + Arrays.toString(expandedGrades));
363+
364+
// Calculate average of all grades
365+
double sum = 0;
366+
for (int grade : expandedGrades) {
367+
sum += grade;
368+
}
369+
double average = sum / expandedGrades.length;
370+
System.out.println("Average grade: " + average);
371+
```
372+
373+
This exercise demonstrates the important Java concept that arrays have fixed sizes, and when you need more space, you create a new array and copy the data. The old array will be automatically cleaned up by Java's garbage collector.

IntroAndWorkBook/pdf/index.pdf

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)
X Tutup