Tạo Immutable Set trong Android
Bài viết này minh họa cách tạo một Immutable Set (tập hợp chỉ đọc, không thể sửa đổi) trong Android sử dụng phương thức factory Collections.unmodifiableSet(). Immutable Set rất hữu ích khi bạn muốn bảo vệ dữ liệu khỏi việc thay đổi ngẫu nhiên.
Bước 1: Tạo dự án mới
Trong Android Studio, chọn File → New Project và điền thông tin cần thiết.
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.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
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 Set từ mảng
Set<String> set = new HashSet<>(Arrays.asList(mobileArray));
// Tạo Immutable Set (chỉ đọc)
Set<String> readOnlySet = Collections.unmodifiableSet(set);
// Chuyển về mảng để hiển thị lên ListView
String[] array = new String[readOnlySet.size()];
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, readOnlySet.toArray(array));
list.setAdapter(adapter);
}
}
Giải thích quan trọng
Collections.unmodifiableSet(set)trả về một view chỉ đọc của set gốc.- Mọi cố gắng sửa đổi (add, remove, clear) trên
readOnlySetsẽ ném raUnsupportedOperationException. - Set gốc (
set) vẫn có thể thay đổi, và thay đổi đó sẽ phản ánh lên immutable view.
Chạy ứng dụng
Kết nối thiết bị, nhấn Run trên Android Studio. Màn hình sẽ hiển thị danh sách các hệ điều hành di động từ Immutable Set.
