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

查看:361
本文介绍了在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

还有另一个ArrayList categoryIDsArray,其中包含类别ID整数.

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.

子类别会变得更加复杂,因为它们的ID以40左右的开头.

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

其他信息:

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

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<Integer, String>是双向映射,使您能够从名称中获取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天全站免登陆