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

Cách tìm phần tử giữa trong mảng (Array) Android

Giới thiệu

Ví dụ này minh họa cách tìm phần tử ở giữa (middle element) của một mảng (array) trong Android.

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

Mở Android Studio, chọn File → New Project và điền đầy đủ thông tin cần thiết.

Bước 2: Thiết kế 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:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:gravity="center"
        android:padding="16dp" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        // Mảng số nguyên
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};

        // Tính index giữa
        int middleIndex = array.length / 2;
        int middleElement = array[middleIndex];

        TextView textView = findViewById(R.id.text);
        textView.setText("Mảng: [1, 2, 3, 4, 5, 6, 7, 8]" + 
            "\nĐộ dài: " + array.length + 
            "\nIndex giữa (length/2): " + middleIndex + 
            "\nPhần tử giữa: " + middleElement);
    }
}

Chạy ứng dụng

Kết nối thiết bị Android thật với máy tính. Trong Android Studio, nhấn Run và chọn thiết bị để chạy.

Kết quả

Mảng: [1, 2, 3, 4, 5, 6, 7, 8] (8 phần tử - số chẵn)

Index giữa = 8/2 = 4

Phần tử tại index 4: 5

Giải thích

  • Array.length: Thuộc tính (không phải phương thức) cho độ dài mảng - O(1)
  • array[index]: Truy cập ngẫu nhiên O(1) - ưu điểm lớn so với LinkedList
  • Số phần tử chẵn: length/2 trả về phần tử bên phải giữa (index 4 trong 0-7)
  • Số phần tử lẻ: length/2 trả về chính giữa (ví dụ 7 phần tử → index 3)

Xử lý trường hợp mảng rỗng

if (array.length == 0) {
    textView.setText("Mảng rỗng");
} else {
    int mid = array.length / 2;
    textView.setText("Phần tử giữa: " + array[mid]);
}

Lưu ý: Code gốc import java.lang.reflect.Array và java.util.LinkedList không cần thiết. Đã loại bỏ @RequiresApi không cần thiết. Array access hoạt động mọi API level.