COMPSCI4039 Programming
Arrays Part 3
Objects inside arrays
Copyright By PowCoder代写 加微信 powcoder
• Remember we can store objects in arrays:
• Specifically, we are storing the references to the objects.
Person[] personArray = new Person[3]; personArray[0] = new Person(“Fred”, 103); personArray[2] = new Person(“Bill”, 56);
Person reference = personArray[0];
• The code here creates a reference to an object, reference.
• This points to the same object, as the reference held in the array itself.
Objects inside arrays
• When we initially create the array:
• It is empty, there is nothing in it.
• There are no object references within the containers.
Person[] personArray = new Person[3]; Person reference = personArray[0];
//won’t work!
• Be mindful when creating variables.
• Make sure the thing you are pointing to
• We can create objects or point them to objects that exist in the array.
Arrays with multiple dimensions
• Arrays we have been looking at so far are one dimensional.
• Therefore, we access them with a single offset value.
• But arrays in Java can have multiple dimensions
• Arrays themselves can contain arrays…
• Very useful feature, depending on what you are doing.
• Can be very challenging to keep a mental model of where everything is!
Mental model
int[] intArray = new int[3];
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;
• Code above creates the array to the right.
• Code below creates an array, associated with each array offset.
int[][] intArray = new int[3][3];
intArray[0][0] = 1;
intArray[0][1] = 2;
intArray[0][2] = 3;
Mental model
int[] intArray = new int[3];
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;
• Code above creates the array to the right.
• Code below creates an array, associated with each array offset.
• The sizes do not need to be the same.
int[][] intArray = new int[3][5];
intArray[0][0] = 1;
intArray[0][1] = 2;
intArray[0][2] = 3;
Mental model
Mental model
Mental model
Mental model
Mental model
Mental model
You can go crazy with dimensions
• You can have many dimensions in an array. • As many as you can keep track of mentally!
• Not always used as can be a nightmare to organize!
int[][][][][] intArray = new int[3][5][2][1][3];
intArray[0][0][0][0][2] = 100;
//This code is fine! But not always used!
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com