Title here
Summary here
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Slices {
public static void main(String[] args) {
// In Java, we use ArrayList as a dynamic array equivalent to Go's slices
// An uninitialized ArrayList is empty but not null
ArrayList<String> s = new ArrayList<>();
System.out.println("uninit: " + s + " " + s.isEmpty() + " " + (s.size() == 0));
// To create an empty ArrayList with non-zero capacity, we can use the constructor
s = new ArrayList<>(3);
System.out.println("emp: " + s + " len: " + s.size() + " cap: " + ((ArrayList<String>) s).ensureCapacity(3));
// We can add and get elements just like with arrays
s.add("a");
s.add("b");
s.add("c");
System.out.println("set: " + s);
System.out.println("get: " + s.get(2));
// size() returns the length of the ArrayList
System.out.println("len: " + s.size());
// We can add more elements to the ArrayList
s.add("d");
s.addAll(Arrays.asList("e", "f"));
System.out.println("apd: " + s);
// We can create a copy of an ArrayList
ArrayList<String> c = new ArrayList<>(s);
System.out.println("cpy: " + c);
// Sublist in Java is similar to slice in Go
List<String> l = s.subList(2, 5);
System.out.println("sl1: " + l);
l = s.subList(0, 5);
System.out.println("sl2: " + l);
l = s.subList(2, s.size());
System.out.println("sl3: " + l);
// We can declare and initialize an ArrayList in a single line
ArrayList<String> t = new ArrayList<>(Arrays.asList("g", "h", "i"));
System.out.println("dcl: " + t);
// Java doesn't have a built-in slices package, but we can compare ArrayLists
ArrayList<String> t2 = new ArrayList<>(Arrays.asList("g", "h", "i"));
if (t.equals(t2)) {
System.out.println("t == t2");
}
// Multi-dimensional ArrayLists
ArrayList<ArrayList<Integer>> twoD = new ArrayList<>();
for (int i = 0; i < 3; i++) {
twoD.add(new ArrayList<>());
for (int j = 0; j <= i; j++) {
twoD.get(i).add(i + j);
}
}
System.out.println("2d: " + twoD);
}
}
Unlike Go’s slices, Java uses ArrayList
as a dynamic array. ArrayList
provides similar functionality to Go’s slices, but with some differences in syntax and available methods.
To run the program, save it as Slices.java
and use javac
to compile and java
to run:
$ javac Slices.java
$ java Slices
uninit: [] true true
emp: [] len: 0 cap: 3
set: [a, b, c]
get: c
len: 3
apd: [a, b, c, d, e, f]
cpy: [a, b, c, d, e, f]
sl1: [c, d, e]
sl2: [a, b, c, d, e]
sl3: [c, d, e, f]
dcl: [g, h, i]
t == t2
2d: [[0], [1, 2], [2, 3, 4]]
Note that while ArrayList
in Java provides similar functionality to slices in Go, there are some differences:
ArrayList
instead of built-in slice syntax.ArrayList
is managed internally and not directly accessible.subList
method, which returns a view of the original list.slices
package, but ArrayList
provides methods for comparison and manipulation.Despite these differences, ArrayList
in Java can be used to achieve similar functionality to Go’s slices in most cases.