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

Tạo Immutable List (Danh sách bất biến) trong Android bằng factory method

Tạo Immutable List trong Android

Hướng dẫn này trình bày cách tạo Immutable List (danh sách chỉ đọc) trong Android sử dụng Collections.unmodifiableList(). Kỹ thuật này giúp đảm bảo tính toàn vẹn dữ liệu khi chia sẻ danh sách giữa các thành phần ứng dụng.

Bước 1: Tạo dự án mới

Android Studio → File → New Project → điền thông tin dự án.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="100dp"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Bước 3: Code logic (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ListView list;
    String[] mobileArray = {"Android", "IPhone", "WindowsMobile", "Blackberry",
            "WebOS", "Ubuntu", "Windows7", "Max OS X"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = findViewById(R.id.list);

        // Tạo ArrayList từ mảng
        List<String> list1 = new ArrayList<>(Arrays.asList(mobileArray));

        // Tạo Immutable List
        List<String> readOnlyList = Collections.unmodifiableList(list1);

        // Hiển thị lên ListView
        String[] array = new String[readOnlyList.size()];
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, readOnlyList.toArray(array));
        list.setAdapter(adapter);
    }
}

Lưu ý quan trọng

  • Immutable List ngăn chặn các thao tác sửa đổi cấu trúc (add, remove, set).
  • Nếu các đối tượng bên trong list là mutable (có thể thay đổi nội bộ), immutable list không bảo vệ được chúng.
  • Dùng List.of() (Java 9+) để tạo immutable list trực tiếp, ngắn gọn hơn.

Chạy ứng dụng

Chạy app trên thiết bị thật. Kết quả hiển thị danh sách hệ điều hành di động từ Immutable List.

Tạo Immutable List (Danh sách bất biến) trong Android bằng factory method