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

วิธีลบข้อมูลซ้ำจาก Linked List ที่จัดเรียงแล้วใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีลบข้อมูลซ้ำจาก LinkedList ที่จัดเรียงแล้วใน Android โดยใช้ LinkedHashSet เพื่อรักษาลำดับและลบค่าซ้ำ

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

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

ในโค้ดข้างต้น ใช้ TextView เพื่อแสดงผล Linked List ที่ไม่มีค่าซ้ำ

ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.LinkedHashSet;
import java.util.LinkedList;

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinkedList<Integer> list = new LinkedList<>();
        list.add(11);
        list.add(11);
        list.add(11);
        list.add(14);
        list.add(14);
        list.add(20);

        // ใช้ LinkedHashSet เพื่อลบซ้ำและรักษาลำดับ
        LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(list);

        TextView textView = findViewById(R.id.text);
        textView.setText(hashSet.toString());
    }
}

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

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอ

วิธีลบข้อมูลซ้ำจาก Linked List ที่จัดเรียงแล้วใน Android

ผลลัพธ์จะแสดง [11, 14, 20] - ค่าถูกลบซ้ำออกแล้วและรักษาลำดับเดิมไว้