Arrays

An array is a data type that represents an ordered collection of elements.

Declaring and Using Arrays

In Java, an array is also a data type that represents an ordered collection of elements. You can declare an array in Java using the new keyword, followed by the type of elements it will hold and the size of the array:

String[] names = new String[] {"Zayn", "Mary", "Adam"};
int[] ages = new int[] {30, 25, 35};
boolean[] isEmployed = new boolean[] {true, false, true};

To use the array, we use the [index] operator to access the elements of an array by their index, which starts at 0.

System.out.println(names[0]); // Output: "Zayn"
System.out.println(ages[1]); // Output: 25
System.out.println(isEmployed[2]); // Output: true

In TypeScript, we can also declare an array in TypeScript using the [] notation, followed by the type of elements it will hold:

let names: string[] = ["Zayn", "Mary", "Bob"];
let ages: number[] = [30, 25, 35];
let isEmployed: boolean[] = [true, false, true];

In TypeScript, we also use the [] operator to access the elements of an array by their index starting at 0:

console.log(names[0]); // Output: "Zayn"
console.log(ages[1]); // Output: 25
console.log(isEmployed[2]); // Output: true

Slices

TypeScript also provides the built-in slice() method, which you can use to create a copy of an array. The slice() method takes two optional arguments, which represent the start and end indices of the slice. If you omit these arguments, the slice() method will return a copy of the entire array.

let names: string[] = ["Zayn", "Mary", "Bob"];

let copy = names.slice();
console.log(copy); // Output: ["Zayn", "Mary", "Bob"]

let slice = names.slice(1, 3);
console.log(slice); // Output: ["Mary", "Bob"]

In the example above, the slice() method creates a copy of the names array and returns it as a new array. You can then use the slice() method to create a slice of the array, which is a subset of the array with a specific range of elements.

The slice() method is special because it creates a copy of an array without modifying the original array. This is useful when you want to create a new array based on an existing array, but you don’t want to modify the original array.

Java has a similar concept of slices. You can use the Arrays.copyOfRange() method to create a subarray of an array in Java. The copyOfRange() method takes three arguments: the original array, the start index, and the end index. It returns a new array with the elements from the original array within the specified range.

int[] numbers = {3, 5, 1, 2, 4};

int[] copy = Arrays.copyOfRange(numbers, 0, numbers.length);
System.out.println(Arrays.toString(copy)); // Output: [3, 5, 1, 2, 4]

int[] subarray = Arrays.copyOfRange(numbers, 1, 3);
System.out.println(Arrays.toString(subarray)); // Output: [5, 1]

Common TypeScript Array Methods

Here’s a list of common array methods in TypeScript, with examples and their equivalent methods in Java:

push()

Adds one or more elements to the end of an array and returns the new length of the array.

let numbers: number[] = [1, 2, 3];
let length = numbers.push(4, 5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(length); // Output: 5

Java arrays don’t have such method. The closest would be ArrayList.add() method if you are using the ArrayList class instead of Arrays:

List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3));
numbers.add(4);
numbers.add(5);
System.out.println(numbers); // Output: [1, 2, 3, 4, 5]
System.out.println(numbers.size()); // Output: 5

pop()

Removes the last element of an array and returns it.

let numbers: number[] = [1, 2, 3];
let last = numbers.pop();
console.log(numbers); // Output: [1, 2]
console.log(last); // Output: 3

This method doesn’t exist in Java Arrays, but you can use ArrayList and its ArrayList.remove() to achieve the same effect:

List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3));
int last = numbers.remove(numbers.size() - 1);
System.out.println(numbers); // Output: [1, 2]
System.out.println(last); // Output: 3

indexOf()

Returns the index of the first element in an array that matches a specified value, or -1 if no such element exits.

let names: string[] = ["John", "Mary", "Bob"];
let index = names.indexOf("Mary");
console.log(index); // Output: 1

Again, no such method exists in Java Arrays, but you can use the List.indexOf() if you are using ArrayList class.

List<String> names = Arrays.asList("John", "Mary", "Bob");
int index = names.indexOf("Mary");
System.out.println(index); // Output: 1

join()

The join() method concatenates the elements of the names array into a single string, separated by the specified delimiter.

let names: string[] = ["John", "Mary", "Bob"];
let str = names.join(","); // delimiter is comma
console.log(str); // Output: "John,Mary,Bob"

In Java, we can use the Collectors.joining() method to join the elements of a stream into a single string:

List<String> names = Arrays.asList("John", "Mary", "Bob");
String str = names.stream().collect(Collectors.joining(", "));
System.out.println(str); // Output: "John, Mary, Bob"

Array Destructing

Suppose, you want to extract values from an array and assign them to separate named variables. Here’s one way to do it in Java:

String[] names = {"John", "Mary", "Bob"};
String first = names[0];
String second = names[1];
String third = names[2];

System.out.println(first); // Output: "John"
System.out.println(second); // Output: "Mary"
System.out.println(third); // Output: "Bob"

Notice how much code we had to write just to do a simple task!

In TypeScript, array destructuring is a way to extract values from an array and assign them to separate variables. You can use array destructuring to conveniently access the elements of an array and to assign them to variables in a single statement.

let names: string[] = ["John", "Mary", "Bob"];
let [first, second, third] = names; // destructure!

console.log(first); // Output: "John"
console.log(second); // Output: "Mary"
console.log(third); // Output: "Bob"

In the example above, the variables first, second, and third are destructured from the names array and are assigned the values of the corresponding elements in the array.

You can also use array destructuring with the rest operator (...) to extract the remaining elements of an array into a new array:

let names: string[] = ["John", "Mary", "Bob"];
let [first, ...others] = names;

console.log(first); // Outputs "John"
console.log(others); // Output in an Array: ["Mary", "Bob"]

In the example above, the first variable is destructured from the names array and is assigned the value of the first element in the array. The rest operator (...) is used to extract the remaining elements of the names array into a new array called others.

Because array destructuring is not supported in Java and not used commonly. On the hand hand, array destructing is used widely in TypeScript. Many methods return an array which is destructured to give the returned values readable names instead of arr[0] and arr[1]. For example, React uses array destructing in React Hooks to return state and setState variable and function respectively.

const [state, setState] = useState(0);

Licenses and Attributions


Speak Your Mind

-->