在 Java 中关联来自两个数组列表的项目 [英] Correlating items from two arraylists in Java

查看:36
本文介绍了在 Java 中关联来自两个数组列表的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 android 应用程序中,我有一个包含类别名称的微调器(下拉菜单).用户按名称选择一个类别,比如食物和饮料"

In my android app I have a spinner (drop-down) that contains category names. User selects a category by its name, say "Food and Drink"

这些类别包含在一个 ArrayList categoryNamesArray

those categories are contained in an ArrayList categoryNamesArray

还有另一个包含类别 ID 整数的 ArrayList categoryIDsArray.

there is another ArrayList categoryIDsArray which contains the category ID integers.

两个匹配项的顺序,这意味着类别 1 是类别汽车,它应该是.

The ordering for both matches, meaning category 1 is category Automotive, which it is supposed to be.

当用户按名称选择类别时,我需要将类别 ID 发送到数据库.我该怎么做.

I need to send the category ID to the database, when the user chooses a category by name. How can I do that.

Subcategories 会变得更复杂,因为它们的 ID 以 40 多岁开头.

It gets more complicated with Subcategories, because their IDs start with 40-something.

附加信息:

我从服务器中提取 id 并将它们放入一个数组列表中,然后我从服务器中提取类别名称并将它们放入另一个数组列表中.然后将两个数组列表放在一个 Object[] 中,并将它们传递给需要它们的 Activity

I pull the ids from the server and put them in an arraylist, then I pull the category names from the server and put them in another arraylist. Then put the two arraylists in one Object[] and pass them to the activity that needs them

推荐答案

如果你因为遗留问题或其他原因,受限于 ArrayList 数据结构,你可以通过这样做来获取相应的 id

If you are, for legacy or some other reason, restricted to the ArrayList data structure, you can get the corresponding id by doing

String chosenName; // user selects this
Integer id = categoryIDsArray.get(categoryNamesArray.indexOf(chosenName));

但是,如果您将代码更改为具有其中之一会更好

But, it will be hugely better if you change the code to have either

  1. 类别"对象(由 Eluvatar 建议),或
  2. A BiMap 这是一个双向映射,使您能够从名称中获取 id,反之亦然.
  1. A "Category" object (as suggested by Eluvatar), or
  2. A BiMap<Integer, String> which is a bidirectional map enabling you to get the id from a name, and vice versa.

这篇关于在 Java 中关联来自两个数组列表的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆