Collections.unmodifiableSet()
Tạo view chỉ đọc (read-only) của một Set. Mọi thao tác sửa đổi (add, remove, clear) trên set trả về sẽ ném UnsupportedOperationException. Dùng để bảo vệ dữ liệu không bị thay đổi vô tình.
Ví dụ: TreeSet + unmodifiableSet cho ListView
MainActivity.java
package com.example.unmodifiablesetdemo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class MainActivity extends AppCompatActivity {
EditText name;
ArrayAdapter<String> adapter;
ArrayList<String> dataList;
SortedSet<String> sortedSet = new TreeSet<>(); // Tự động sắp xếp & loại trùng
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<>();
name = findViewById(R.id.name);
listView = findViewById(R.id.listView);
findViewById(R.id.refresh).setOnClickListener(v -> {
if (adapter != null) adapter.notifyDataSetChanged();
});
findViewById(R.id.save).setOnClickListener(v -> {
String input = name.getText().toString().trim();
if (!input.isEmpty()) {
sortedSet.add(input); // TreeSet: unique + sorted
// Tạo view chỉ đọc
Set<String> unmodifiable = Collections.unmodifiableSet(sortedSet);
dataList.clear();
dataList.addAll(unmodifiable); // Copy dữ liệu vào ArrayList
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
Toast.makeText(this, "Đã thêm (đã sắp xếp, không trùng)", Toast.LENGTH_SHORT).show();
} else {
name.setError("Nhập tên");
}
});
}
}
Kết quả
Nhập: "delta", "alpha", "epsilon", "beta", "alpha" (trùng)
ListView hiển thị theo thứ tự A-Z, không trùng:
alpha
beta
delta
epsilon
Đặc điểm quan trọng
unmodifiableSetlà view - thay đổi set gốc (sortedSet) sẽ phản ánh lên view.- Không phải deep copy - dữ liệu không được sao chép, chỉ bọc lại.
- Set gốc vẫn có thể sửa đổi bình thường.
Các phương thức unmodifiable khác
unmodifiableList(List)unmodifiableMap(Map)unmodifiableCollection(Collection)unmodifiableSortedSet(SortedSet)- giữ tính sắp xếp
Khi nào dùng?
- Trả về dữ liệu từ API/module nội bộ, không muốn caller sửa đổi.
- Chia sẻ cấu trúc dữ liệu giữa thread (kết hợp với synchronization).
- Đảm bảo tính bất biến (immutability) trong thiết kế functional.
Lưu ý
Nếu cần bản sao hoàn toàn độc lập: new HashSet<>(originalSet).