0
# JSON Array Operations
1
2
Create, modify, and iterate over JSON arrays with type-safe element access, fluent construction, and comprehensive array management capabilities.
3
4
## Capabilities
5
6
### Array Creation
7
8
Create JSON arrays with constructors and static factory methods.
9
10
```java { .api }
11
/**
12
* Creates an empty JSON array
13
*/
14
JsonArray();
15
16
/**
17
* Creates a JSON array as a copy of another array
18
* @param array the JSON array to copy
19
*/
20
JsonArray(JsonArray array);
21
22
/**
23
* Creates an unmodifiable view of the given JSON array
24
* @param array the JSON array to wrap
25
* @return unmodifiable JSON array view
26
*/
27
static JsonArray unmodifiableArray(JsonArray array);
28
```
29
30
**Usage Examples:**
31
32
```java
33
import org.hjson.JsonArray;
34
import org.hjson.JsonValue;
35
36
// Create empty array
37
JsonArray emptyArray = new JsonArray();
38
39
// Create array with initial data
40
JsonArray numbers = new JsonArray()
41
.add(1)
42
.add(2)
43
.add(3)
44
.add(4)
45
.add(5);
46
47
// Copy constructor
48
JsonArray numbersCopy = new JsonArray(numbers);
49
50
// Unmodifiable view
51
JsonArray readOnlyNumbers = JsonArray.unmodifiableArray(numbers);
52
```
53
54
### Adding Elements (Fluent Interface)
55
56
Add new elements to JSON arrays with type-specific convenience methods.
57
58
```java { .api }
59
/**
60
* Appends the specified JSON value to the end of this array
61
* @param value the JSON value to be appended to this array
62
* @return the JSON array itself, to enable method chaining
63
*/
64
JsonArray add(JsonValue value);
65
66
/**
67
* Appends the specified string value to the end of this array
68
* @param value the string value to be appended to this array
69
* @return the JSON array itself, to enable method chaining
70
*/
71
JsonArray add(String value);
72
73
/**
74
* Appends the specified int value to the end of this array
75
* @param value the int value to be appended to this array
76
* @return the JSON array itself, to enable method chaining
77
*/
78
JsonArray add(int value);
79
80
/**
81
* Appends the specified long value to the end of this array
82
* @param value the long value to be appended to this array
83
* @return the JSON array itself, to enable method chaining
84
*/
85
JsonArray add(long value);
86
87
/**
88
* Appends the specified float value to the end of this array
89
* @param value the float value to be appended to this array
90
* @return the JSON array itself, to enable method chaining
91
*/
92
JsonArray add(float value);
93
94
/**
95
* Appends the specified double value to the end of this array
96
* @param value the double value to be appended to this array
97
* @return the JSON array itself, to enable method chaining
98
*/
99
JsonArray add(double value);
100
101
/**
102
* Appends the specified boolean value to the end of this array
103
* @param value the boolean value to be appended to this array
104
* @return the JSON array itself, to enable method chaining
105
*/
106
JsonArray add(boolean value);
107
```
108
109
**Usage Examples:**
110
111
```java
112
import org.hjson.JsonArray;
113
import org.hjson.JsonObject;
114
import org.hjson.JsonValue;
115
116
// Build arrays with fluent interface
117
JsonArray mixedArray = new JsonArray()
118
.add("Hello")
119
.add(42)
120
.add(true)
121
.add(3.14)
122
.add(JsonValue.NULL);
123
124
// Create array of objects
125
JsonArray users = new JsonArray();
126
for (int i = 1; i <= 3; i++) {
127
JsonObject user = new JsonObject()
128
.add("id", i)
129
.add("name", "User " + i)
130
.add("active", i % 2 == 1);
131
users.add(user);
132
}
133
134
// Array of arrays (nested structure)
135
JsonArray matrix = new JsonArray()
136
.add(new JsonArray().add(1).add(2).add(3))
137
.add(new JsonArray().add(4).add(5).add(6))
138
.add(new JsonArray().add(7).add(8).add(9));
139
```
140
141
### Setting/Replacing Elements
142
143
Replace existing elements at specific indices with set methods.
144
145
```java { .api }
146
/**
147
* Replaces the element at the specified position with the specified JSON value
148
* @param index the index of the element to replace
149
* @param value the JSON value to be stored at the specified position
150
* @return the JSON array itself, to enable method chaining
151
* @throws IndexOutOfBoundsException if the index is out of range
152
*/
153
JsonArray set(int index, JsonValue value);
154
155
/**
156
* Replaces the element at the specified position with the specified string value
157
* @param index the index of the element to replace
158
* @param value the string value to be stored at the specified position
159
* @return the JSON array itself, to enable method chaining
160
* @throws IndexOutOfBoundsException if the index is out of range
161
*/
162
JsonArray set(int index, String value);
163
164
/**
165
* Replaces the element at the specified position with the specified int value
166
* @param index the index of the element to replace
167
* @param value the int value to be stored at the specified position
168
* @return the JSON array itself, to enable method chaining
169
* @throws IndexOutOfBoundsException if the index is out of range
170
*/
171
JsonArray set(int index, int value);
172
173
/**
174
* Replaces the element at the specified position with the specified long value
175
* @param index the index of the element to replace
176
* @param value the long value to be stored at the specified position
177
* @return the JSON array itself, to enable method chaining
178
* @throws IndexOutOfBoundsException if the index is out of range
179
*/
180
JsonArray set(int index, long value);
181
182
/**
183
* Replaces the element at the specified position with the specified float value
184
* @param index the index of the element to replace
185
* @param value the float value to be stored at the specified position
186
* @return the JSON array itself, to enable method chaining
187
* @throws IndexOutOfBoundsException if the index is out of range
188
*/
189
JsonArray set(int index, float value);
190
191
/**
192
* Replaces the element at the specified position with the specified double value
193
* @param index the index of the element to replace
194
* @param value the double value to be stored at the specified position
195
* @return the JSON array itself, to enable method chaining
196
* @throws IndexOutOfBoundsException if the index is out of range
197
*/
198
JsonArray set(int index, double value);
199
200
/**
201
* Replaces the element at the specified position with the specified boolean value
202
* @param index the index of the element to replace
203
* @param value the boolean value to be stored at the specified position
204
* @return the JSON array itself, to enable method chaining
205
* @throws IndexOutOfBoundsException if the index is out of range
206
*/
207
JsonArray set(int index, boolean value);
208
```
209
210
**Usage Examples:**
211
212
```java
213
import org.hjson.JsonArray;
214
215
// Create array with initial values
216
JsonArray scores = new JsonArray()
217
.add(85)
218
.add(92)
219
.add(76)
220
.add(88);
221
222
// Update specific elements
223
scores.set(0, 87) // Update first score
224
.set(2, 78); // Update third score
225
226
// Conditional updates
227
if (someCondition) {
228
scores.set(scores.size() - 1, 95); // Update last element
229
}
230
231
// Replace with different types (be careful with type consistency)
232
JsonArray mixed = new JsonArray()
233
.add("initial")
234
.add(100);
235
236
mixed.set(0, "updated") // String to string
237
.set(1, 200); // Number to number
238
```
239
240
### Accessing Elements
241
242
Retrieve array elements by index with bounds checking.
243
244
```java { .api }
245
/**
246
* Returns the value of the element at the specified position in this array
247
* @param index the index of the array element to return
248
* @return the value of the element at the specified position
249
* @throws IndexOutOfBoundsException if the index is out of range
250
*/
251
JsonValue get(int index);
252
```
253
254
**Usage Examples:**
255
256
```java
257
import org.hjson.JsonArray;
258
import org.hjson.JsonValue;
259
import org.hjson.JsonObject;
260
261
JsonArray data = JsonValue.readHjson("""
262
[
263
{ name: "Alice", score: 95 },
264
{ name: "Bob", score: 87 },
265
{ name: "Charlie", score: 91 }
266
]
267
""").asArray();
268
269
// Safe element access with bounds checking
270
for (int i = 0; i < data.size(); i++) {
271
JsonValue element = data.get(i);
272
if (element.isObject()) {
273
JsonObject person = element.asObject();
274
String name = person.getString("name", "Unknown");
275
int score = person.getInt("score", 0);
276
System.out.println(name + ": " + score);
277
}
278
}
279
280
// Access specific elements
281
if (data.size() > 0) {
282
JsonValue first = data.get(0);
283
JsonValue last = data.get(data.size() - 1);
284
285
// Process first and last elements
286
System.out.println("First: " + first);
287
System.out.println("Last: " + last);
288
}
289
290
// Handle potential IndexOutOfBoundsException
291
try {
292
JsonValue element = data.get(10); // May throw exception
293
} catch (IndexOutOfBoundsException e) {
294
System.err.println("Index out of bounds: " + e.getMessage());
295
}
296
```
297
298
### Array Management
299
300
Remove elements and query array structure.
301
302
```java { .api }
303
/**
304
* Removes the element at the specified position from this array
305
* Shifts any subsequent elements to the left (subtracts one from their indices)
306
* @param index the index of the element to be removed
307
* @return the JSON array itself, to enable method chaining
308
* @throws IndexOutOfBoundsException if the index is out of range
309
*/
310
JsonArray remove(int index);
311
312
/**
313
* Returns the number of elements in this array
314
* @return the number of elements in this array
315
*/
316
int size();
317
318
/**
319
* Returns true if this array contains no elements
320
* @return true if this array is empty
321
*/
322
boolean isEmpty();
323
324
/**
325
* Returns an unmodifiable List view of the values in this array
326
* Changes to the original array are reflected in the returned list
327
* @return unmodifiable list view of array elements
328
*/
329
List<JsonValue> values();
330
```
331
332
**Usage Examples:**
333
334
```java
335
import org.hjson.JsonArray;
336
import java.util.List;
337
338
JsonArray items = new JsonArray()
339
.add("apple")
340
.add("banana")
341
.add("cherry")
342
.add("date");
343
344
// Query array structure
345
System.out.println("Size: " + items.size()); // Output: Size: 4
346
System.out.println("Empty: " + items.isEmpty()); // Output: Empty: false
347
348
// Remove elements (be careful with indices shifting)
349
items.remove(1); // Removes "banana", "cherry" shifts to index 1
350
System.out.println("After removal: " + items.size()); // Output: After removal: 3
351
352
// Remove from end to avoid index shifting issues
353
while (!items.isEmpty()) {
354
items.remove(items.size() - 1); // Always remove last element
355
}
356
System.out.println("After clearing: " + items.isEmpty()); // Output: After clearing: true
357
358
// Get list view for read-only operations
359
JsonArray numbers = new JsonArray().add(1).add(2).add(3);
360
List<JsonValue> numberList = numbers.values();
361
System.out.println("List size: " + numberList.size()); // Output: List size: 3
362
363
// Use list for enhanced operations (read-only)
364
for (JsonValue value : numberList) {
365
if (value.isNumber()) {
366
System.out.println("Number: " + value.asInt());
367
}
368
}
369
```
370
371
### Iteration
372
373
Iterate over array elements with enhanced for-loop support.
374
375
```java { .api }
376
/**
377
* Returns an iterator over the elements in this array in proper sequence
378
* @return iterator over JsonValue elements
379
*/
380
Iterator<JsonValue> iterator();
381
```
382
383
**Usage Examples:**
384
385
```java
386
import org.hjson.JsonArray;
387
import org.hjson.JsonValue;
388
import java.util.Iterator;
389
390
JsonArray mixed = new JsonArray()
391
.add("text")
392
.add(42)
393
.add(true)
394
.add(3.14)
395
.add(JsonValue.NULL);
396
397
// Enhanced for-loop iteration
398
for (JsonValue element : mixed) {
399
if (element.isString()) {
400
System.out.println("String: " + element.asString());
401
} else if (element.isNumber()) {
402
System.out.println("Number: " + element.asDouble());
403
} else if (element.isBoolean()) {
404
System.out.println("Boolean: " + element.asBoolean());
405
} else if (element.isNull()) {
406
System.out.println("Null value found");
407
}
408
}
409
410
// Iterator-based iteration with index tracking
411
Iterator<JsonValue> iterator = mixed.iterator();
412
int index = 0;
413
while (iterator.hasNext()) {
414
JsonValue element = iterator.next();
415
System.out.println("Element " + index + ": " + element +
416
" (type: " + element.getType() + ")");
417
index++;
418
}
419
420
// Process array of objects
421
JsonArray users = new JsonArray()
422
.add(new JsonObject().add("name", "Alice").add("age", 25))
423
.add(new JsonObject().add("name", "Bob").add("age", 30));
424
425
for (JsonValue userValue : users) {
426
if (userValue.isObject()) {
427
JsonObject user = userValue.asObject();
428
String name = user.getString("name", "Unknown");
429
int age = user.getInt("age", 0);
430
System.out.println(name + " is " + age + " years old");
431
}
432
}
433
```
434
435
## Type Checking and Conversion
436
437
JsonArray inherits type checking and conversion methods from JsonValue:
438
439
```java { .api }
440
// Type checking (always returns true for JsonArray)
441
boolean isArray();
442
JsonType getType(); // Returns JsonType.ARRAY
443
444
// Safe conversion (returns this)
445
JsonArray asArray();
446
447
// Array equality and hashing
448
boolean equals(Object obj);
449
int hashCode();
450
```
451
452
## Common Patterns and Use Cases
453
454
### Building Arrays from Collections
455
456
```java
457
import java.util.Arrays;
458
import java.util.List;
459
460
// From Java collections
461
List<String> javaList = Arrays.asList("a", "b", "c");
462
JsonArray jsonArray = new JsonArray();
463
for (String item : javaList) {
464
jsonArray.add(item);
465
}
466
467
// From arrays
468
int[] numbers = {1, 2, 3, 4, 5};
469
JsonArray jsonNumbers = new JsonArray();
470
for (int num : numbers) {
471
jsonNumbers.add(num);
472
}
473
```
474
475
### Array Filtering and Transformation
476
477
```java
478
// Filter array elements
479
JsonArray source = new JsonArray().add(1).add(2).add(3).add(4).add(5);
480
JsonArray filtered = new JsonArray();
481
482
for (JsonValue value : source) {
483
if (value.isNumber() && value.asInt() % 2 == 0) {
484
filtered.add(value);
485
}
486
}
487
488
// Transform array elements
489
JsonArray strings = new JsonArray().add("apple").add("banana").add("cherry");
490
JsonArray upperCase = new JsonArray();
491
492
for (JsonValue value : strings) {
493
if (value.isString()) {
494
upperCase.add(value.asString().toUpperCase());
495
}
496
}
497
```
498
499
### Nested Array Operations
500
501
```java
502
// Create nested arrays
503
JsonArray matrix = new JsonArray();
504
for (int row = 0; row < 3; row++) {
505
JsonArray rowArray = new JsonArray();
506
for (int col = 0; col < 3; col++) {
507
rowArray.add(row * 3 + col + 1);
508
}
509
matrix.add(rowArray);
510
}
511
512
// Access nested elements
513
for (int i = 0; i < matrix.size(); i++) {
514
JsonValue rowValue = matrix.get(i);
515
if (rowValue.isArray()) {
516
JsonArray row = rowValue.asArray();
517
for (int j = 0; j < row.size(); j++) {
518
System.out.print(row.get(j).asInt() + " ");
519
}
520
System.out.println();
521
}
522
}
523
```
524
525
## Thread Safety and Performance
526
527
- **Thread Safety**: JsonArray is **not** thread-safe and requires external synchronization for concurrent access
528
- **Mutability**: JsonArray instances are mutable - methods like `add()`, `set()`, and `remove()` modify the array
529
- **Performance**: Element access is O(1), but removal from the middle causes O(n) shifting
530
- **Memory**: Arrays grow dynamically as elements are added
531
- **Defensive Copying**: Use the copy constructor or `unmodifiableArray()` for safe sharing
532
533
## Best Practices
534
535
1. **Fluent Interface**: Chain method calls for readable array construction
536
2. **Bounds Checking**: Always check `size()` before accessing elements by index
537
3. **Type Consistency**: Try to maintain consistent element types within arrays when possible
538
4. **Index Management**: When removing multiple elements, remove from the end to avoid index shifting
539
5. **Null Handling**: Use `JsonValue.NULL` for explicit null values rather than Java null
540
6. **Iteration**: Prefer enhanced for-loops over manual index iteration when possible
541
7. **Unmodifiable Views**: Use `unmodifiableArray()` when passing arrays to untrusted code
542
8. **Performance**: For frequent modifications, consider building the array in one pass rather than multiple add/remove operations