How long the DVD is?
Array Capacity
Java
DVD[] array = new DVD[6]
Go
DVDa := [6]int{}
DVDs := make([]int, 0, 6)
- Declare an integer slice of Capacity 6 and length 0
- Arrays in Go are static. This means you can store the same data consecutively within a fixed array size.
- Unlike an array, 'Slice' does not specify a fixed size in advance, and can dynamically change the size as needed afterward, and partial extraction is possible.
Java
int capacity = array.length;
System.out.println("The Array has a capacity of " + capacity);
- need to access the capacity of an Array by using .length.
Go
var capacity_a int = cap(DVDa)
var capacity_s int = cap(DVDs)
fmt.Println("The Array has a capacity of", capacity_a)
fmt.Println("The Slice has a capacity of", capacity_s)
Print result
The Array has a capacity of 6
The Slice has a capacity of 6
- go.dev/play/p/ltJxpe3JQpt
Array Length
Java
int[] array = new int[6];
int length = 0;
for (int i = 0; i < 3; i++) {
array[i] = i * i;
length++;
}
System.out.println("The Array has a capacity of " + array.length);
System.out.println("The Array has a length of " + length);
Go
var array [6]int
slice := make([]int, 0, 6)
var length_array = len(array)
var length_slice = len(slice)
fmt.Println("The Array has a length of", length_array)
fmt.Println("The Slice has a length of", length_slice)
for i := 0; i < 3; i++ {
array[i] = i * i
slice = append(slice, i*i)
}
fmt.Println("The Array has a length of", len(array))
fmt.Println("The Slice has a length of", len(slice))
fmt.Println("The Array has a capacity of", cap(array))
fmt.Println("The Slice has a capacity of", cap(slice))
Print result
The Array has a length of 6
The Slice has a length of 0
The Array has a length of 6
The Slice has a length of 3
The Array has a capacity of 6
The Slice has a capacity of 6
- go.dev/play/p/y7wh70WJVep
Handling Array Parameters
Java
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
for (int i = 0; i < nums.length; i++) {
}
}
}
func findMaxConsecutiveOnes(nums []int) int {
for i:=0; i<len(nums); i++ {
}
}
Check array and slice in Go
for _, val := range DVDa {
fmt.Println(val)
}
fmt.Println("Capacity", cap(DVDa), "length", len(DVDa), "Array")
for _, val := range DVDs {
fmt.Println(val)
}
fmt.Println("Capacity", cap(DVDs), "length", len(DVDs), "Nil Slice")
Print result
0
0
0
0
0
0
Capacity 6 length 6 Array
Capacity 6 length 0 Slice
- go.dev/play/p/F_IRGim9Byb