Menu
CoddyTech

Shared and Copied Arrays

Lesson 15 of 48 in Coddy's GDScript for Java Developers course.

Java ArrayList assignment shares a reference, while its collection constructor makes a shallow outer copy. Nested mutable objects remain shared, as with GDScript duplicate. GDScript duplicate(true) recursively copies nested Arrays and Dictionaries but does not automatically construct new instances for every ordinary object. Java List.copyOf also makes an unmodifiable outer list without recursively freezing its elements. Choose copying depth and mutability separately from the API ownership promise.

Complete Java comparison. Compile all listed .java files together with Java 17, then run Main.

Java file Main.java:

import java.util.ArrayList;
import java.util.List;
public class Main {

public static void main(String[] args) { var inner=new ArrayList<Integer>(List.of(1)); var a=new ArrayList<ArrayList<Integer>>(); a.add(inner); var b=new ArrayList<>(a); b.get(0).add(2); System.out.println(a.get(0).size()+" "+b.size()); }
}

Java output:

2 1

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var a: Array = [[1]]
	var b: Array = a.duplicate()
	b[0].append(2)
	print("%d %d" % [a[0].size(),b.size()])

GDScript output:

2 1
challenge icon

Challenge

Easy

Implement ArrayCopy.extended(values:Array)->Array: return independent outer storage with 9 appended. Do not modify the caller. Elements are integers. The locked driver mutates the returned copy and checks the original.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in array_copy.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var original: Array = [2, 3]
	var copied: Array = ArrayCopy.extended(original)
	if copied != [2,3,9]: return false
	copied[0] = 80
	if original != [2,3]: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Java Developers

Practice on your own: Online GDScript compiler