【问题标题】:Element in int Array is not found (while it should)未找到 int 数组中的元素(虽然应该)
【发布时间】:2014-09-25 08:24:47
【问题描述】:

我没有得到正确的索引。谁能告诉我为什么?我希望 0 作为索引,而不是 -1。

int[] id = {R.id.buKeyPadNum1, ...} **(EDIT)**
int index = Arrays.asList(id).indexOf(v.getId());

Log.i("onClick", "v.getId "+ String.valueOf(v.getId())+" ButtonId "+String.valueOf(id[0])
+" Index "+String.valueOf(index));

LogCat: 09-25 08:11:32.039: I/onClick(1680): v.getId 2131296337 ButtonId 2131296337 索引-1

【问题讨论】:

  • index -1 表示它不存在。 v.getId() 的值在您的数组中不存在
  • id.equals(v.getId()) 怎么样,似乎更有意义
  • -1 表示为空且不存在。
  • 真的吗?这就是我发布 LogCat 输出的原因。我尝试在数组 id 中找到 v.getId()。 id[0] 和 v.getId() 在 LogCat 中是一样的......
  • 好吧,也许数据/对象类型不一样

标签: java android arrays


【解决方案1】:

Arrays.asList(id) 返回一个List<long[]>indexOf() 仅适用于 Long[] 对象。见this answer

尝试将Long[] 类型用于id

【讨论】:

  • 是的 "int[] id = {R.id.buKeyPadNum1, ...}" 必须是 "Integer[] id = {}"
【解决方案2】:

考虑这样的代码:

int ix = Arrays.asList(new int[]{1,2}).indexOf(1); 
// result: -1

int ix = Arrays.asList(new Integer[]{1,2}).indexOf(1); 
// result: 0  (found)

可能您的数组包含与 indexOf 参数不同类型的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    相关资源
    最近更新 更多