Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai ArrayList trong JShell Java 9

JShell (REPL Java 9) cho phép thực thi code Java từ shell, hiển thị output ngay. Khởi động: jshell, thoát: /exit. Không cần main() cho snippet nhỏ. Có triển khai được collection: List, Map, Set.

Ví dụ ArrayList trong JShell

C:\Users\User\Desktop\Java 9 QNA> jshell
| Welcome to JShell -- Version 9.0.4
jshell> ArrayList<String> list = new ArrayList<>();
list ==> []

jshell> list.add("Jai"); list.add("Adithya"); list.add("Raja"); list.add("Chaitanya");
$2 ==> true
$3 ==> true
$4 ==> true
$5 ==> true

jshell> list
list ==> [Jai, Adithya, Raja, Chaitanya]

jshell> list.isEmpty()
$7 ==> false

jshell> list.get(3)
$8 ==> "Chaitanya"

jshell> list.get(9)
|  Exception java.lang.IndexOutOfBoundsException: Index 9 out-of-bounds for length 4
|        at Preconditions.outOfBounds (Preconditions.java:64)
|        at ArrayList.get (ArrayList.java:440)
|        at (#9:1)

jshell> list.size()
$10 ==> 4

jshell> if(list.isEmpty()) System.out.println("Empty"); else System.out.println("Not Empty");
Not Empty

Các thao tác ArrayList phổ biến trong JShell

// Tạo List immutable (Java 9+)
jshell> List.of("a", "b", "c")
$1 ==> [a, b, c]

// Thêm nhiều phần tử
jshell> List<String> list = new ArrayList<>(List.of("x", "y"));
jshell> list.addAll(List.of("z", "w"));

// Xóa
jshell> list.remove("x");
jshell> list.removeIf(s -> s.length() == 1);

// Sắp xếp
jshell> list.sort(String::compareTo);

// Stream
jshell> list.stream().filter(s -> s.startsWith("a")).collect(Collectors.toList())

// ListIterator
jshell> ListIterator<String> it = list.listIterator();
jshell> while(it.hasNext()) System.out.println(it.next());

Lưu ý JShell

  • Auto-import java.util.*.
  • Scratch variable $N cho expression không gán biến.
  • Exception hiển thị stack trace ngắn gọn.
  • Tab completion cho method của List.

JShell + Collection API mới (List.of, Map.of, Set.of) = môi trường lý tưởng học collection Java.