当前位置:首页 > 行业动态 > 正文

安卓开发数组的添加数据

数组类型与添加数据方式

基本类型数组(如 int[]

  • 特点:长度固定,无法直接添加元素。
  • 添加数据方式:需创建新数组并复制原数据。
  • 示例代码
    int[] original = {1, 2, 3};
    int[] newArray = Arrays.copyOf(original, original.length + 1);
    newArray[newArray.length 1] = 4; // 添加元素 4

ArrayList(动态数组)

  • 特点:可动态调整容量,支持添加、删除操作。
  • 添加数据方式:使用 add() 方法。
  • 示例代码
    ArrayList<String> list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    // 在指定位置插入
    list.add(1, "Orange"); // 结果:[Apple, Orange, Banana]

JSONArray(处理 JSON 数据)

  • 特点:用于存储 JSON 格式的数组数据。
  • 添加数据方式:使用 put() 方法。
  • 示例代码
    JSONArray jsonArray = new JSONArray();
    jsonArray.put("name");
    jsonArray.put(25); // 添加整数

RecyclerView 的数据集(如 List

  • 特点:需配合适配器使用,添加后需刷新 UI。
  • 添加数据步骤
    1. List 添加数据。
    2. 调用 Adapter.notifyDataSetChanged()NotifyItemInserted
  • 示例代码
    dataList.add("New Item");
    adapter.notifyItemInserted(dataList.size() 1);

数组添加操作对比表

数组类型 添加方法 是否需要手动扩容 适用场景
int[] 创建新数组并复制 固定长度数据
ArrayList add() 否(自动扩容) 动态增删数据
JSONArray put() JSON 数据处理
RecyclerView List.add() + notify... 列表 UI 显示

常见问题与解答

问题 1:如何删除 ArrayList 中的元素?

解答

安卓开发数组的添加数据

  • 按索引删除:list.remove(index)
  • 按对象删除:list.remove(Object)(需重写 equals() 方法)
    示例

    ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
    list.remove(1); // 删除 "B",结果:[A, C]

问题 2:为什么 RecyclerView 添加数据后界面没变化?

解答
可能原因:

安卓开发数组的添加数据

  1. 未调用 notify 方法更新适配器。
  2. 在非主线程操作数据(需切换到主线程)。
    解决方案

    安卓开发数组的添加数据

    dataList.add("New Item");
    adapter.notifyItemInserted(dataList.size() 1); // 刷新指定位置