Tasks studies - laboratory
Declaration and initialization of an array variable:
data_type[] array_name;
data_type array_name[];
Example:
int[] a;
String[] words;
public class Point {
private double X;
private double Y;
public Point(int x, int y) {
X = x;
Y = y;
}
}
Point[] x;
- creates a reference to an array of objects of a specific type, in this case, Point
. However, to use the array, it must be instantiated using the new
operator, i.e., the array must be initialized. At this point, the array size is determined:
words = new String[4];
x = new int[n + 20]; // size determined by an expression
For arrays of primitive types, elements are initialized to default values (0
for numeric types and char
, and false
for boolean
). For arrays of objects, the elements will contain references to null
instead of actual objects.
Declaration and instantiation can be combined into a single statement:
data_type[] arrayName = new data_type[size];
You can also simultaneously declare, create, and initialize an array:
int[] first = {1, 2, 3, 4 + 1, 7, 11};
String[] musketeers = {"Athos", "Porthos", "Aramis"};
Point[] triangle = {new Point(0, 0), new Point(3, 0), new Point(3, 4)};
As shown, the new
operator is not required in such cases!
The array size is stored in the length
field: arrayName.length
.
Array elements are indexed from zero. Access is limited to the range [0, length-1]:
for (int i = 0; i < a.length; i++)
a[i] = i;
Unlike C++ arrays, Java ensures that array index access is valid. If an attempt is made to access an index outside the valid range, an ArrayIndexOutOfBoundsException
is thrown.
Access to array elements is done using the indexing operator [ ]
:
arrayName[element_index];
Copying parts or entire arrays can be performed using loops:
int[] numbers = new int[13];
for (int i = 0; i < 8; i++)
numbers[i] = i * 3;
int[] subset = {24, 27, 30, 33, 36}; // create another array
for (int k = 0; k < 5; k++) // copy values 24, 27, 30, 33, 36
numbers[8 + k] = subset[k];
Alternatively, use the arraycopy()
function from the System
class:
System.arraycopy(src, srcPos, dest, destPos, n);
where:
src
- source arraysrcPos
- starting index in the source arraydest
- destination arraydestPos
- starting index in the destination arrayn
- number of elements to copyExample:
System.arraycopy(subset, 0, numbers, 8, 5);
Calling arraycopy()
for arrays containing objects will copy references, not the objects themselves. This is known as shallow copying.
Java provides additional utility functions for arrays in the java.util.Arrays
class:
void sort(array)
- sorts the array using QuickSort.void sort(array, start, end)
- sorts a portion of the array between indices [start, end).int binarySearch(array, element)
- returns the index of element
in array
if it exists; otherwise, returns a negative value.import java.util.Arrays;
import java.util.Random;
class RandomSorting {
public static void main(String[] args) {
Random random = new Random();
int[] randomNumbers = new int[10];
randomNumbers[0] = 55;
for (int i = 1; i < randomNumbers.length; i++)
randomNumbers[i] = random.nextInt(101);
Arrays.sort(randomNumbers);
System.out.println(Arrays.binarySearch(randomNumbers, 55));
System.out.println(Arrays.binarySearch(randomNumbers, 101));
}
}
Other useful methods:
boolean equals(array1, array2)
- compares two arrays (number and value of elements).String toString(array)
- displays the array content:System.out.print("Array of Natural Numbers: ");
System.out.println(Arrays.toString(randomNumbers));
void fill(array, value)
- assigns the specified value to all elements of the array.void fill(array, start, end, value)
- assigns the value to elements in the range [start, end).Multidimensional arrays are arrays whose elements are arrays themselves:
int[][] matrix = {1, 2, 3}, {4, 5, 6};
boolean[][] chessBoard = new boolean[8][8];
chessBoard[0][0] = true;
chessBoard[1][0] = false;
// ...
class Color {
private String color;
public Color(String c) {
color = c;
}
// ...
}
Color[][][] rgb = new Color[256][256][256];
rgb[0][0][0] = new Color("black");
rgb[255][255][0] = new Color("yellow");
When you need to store an unspecified number of objects or enforce a specific structure among elements, collection classes are used. These are divided into two categories: collections and maps.
Collection
- containers that enforce specific rules, such as ordered lists (List
) or unique sets (Set
).
Map
- objects that store key-value pairs, akin to associative arrays. Keys act as indices, mapping to specific values.
Collections and their methods offer tools for adding, removing, and accessing elements, often paired with iterators. Iterators traverse collection elements efficiently, enhancing flexibility without requiring structural changes.