Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสร้าง Immutable List ด้วย Factory Method ใน Android

การสร้าง Immutable List (รายการไม่เปลี่ยนแปลงได้) ใน Android

ตัวอย่างนี้แสดงวิธีสร้างรายการที่อ่านอย่างเดียว (Read-only) โดยใช้ Collections.unmodifiableList() ซึ่งเป็น Factory Method สำหรับสร้าง Immutable List

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio → File → New Project → กรอกรายละเอียดโปรเจกต์

ขั้นตอนที่ 2: Layout XML (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">
    </ListView>

</LinearLayout>

ขั้นตอนที่ 3: โค้ด Java (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);

        // สร้าง ArrayList จากอาร์เรย์
        List<String> list1 = new ArrayList<>(Arrays.asList(mobileArray));

        // สร้าง Immutable List
        List<String> readOnlyList = Collections.unmodifiableList(list1);

        // แปลงเป็นอาร์เรย์สำหรับ Adapter
        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);
    }
}

การทดสอบแอปพลิเคชัน

รันบนอุปกรณ์ Android จริง จะแสดงรายการใน ListView โดย List จะถูกล็อกไว้ไม่ให้เพิ่ม ลบ หรือแก้ไขข้อมูลได้

วิธีสร้าง Immutable List ด้วย Factory Method ใน Android

ความแตกต่างระหว่าง Immutable Set และ List

คุณสมบัติImmutable SetImmutable List
ลำดับข้อมูลไม่รับประกันรักษาลำดับไว้
ข้อมูลซ้ำไม่ 허용อนุญาต
การเข้าถึงด้วยดัชนีไม่ได้ได้ (get(index))

เมื่อไหร่ควรใช้ Immutable Collections

  • ข้อมูลที่ไม่ควรเปลี่ยนแปลงหลังโหลด (Config, Constants)
  • ส่งข้อมูลระหว่าง Threads อย่างปลอดภัย
  • API ที่คืนค่าข้อมูลให้ Client โดยไม่ต้องการให้แก้ไข