我如何访问 List 的数组元素 [英] How I can access array elements of List
问题描述
我有一个问题:
我有一个用不同值填充的 List Java.例如,我有:
I have a List Java that I have populated with different values. For example, I have:
List<String[]> l = new ArrayList();
String[] lis = new String[3];
lis[0] = "A";
lis[1] = "B";
lis[2] = "C";
l.add(lis);
我也有其他价值观.现在,我只想在此列表中搜索第一个字段.例如,我想要 A 的 indexOf.我曾尝试编写此代码:
and I have other values too. Now, I want to get the search in this list only the first field. For example, I want the A's indexOf. I have tried to write this code:
int index = l.indexOf("A");
但我得到 -1 作为回报.我想知道如何在加载数组时访问列表的字段.
but I get -1 as return. I would like to know how I can access to a field of the list, when I load an array.
推荐答案
我想要 A 的 indexOf.
I want the A's indexOf.
不,你不能得到它,因为它是数组中的一个元素.数组没有 indexOf 方法.列表有那个方法.
No, you can't get it, since it is an element inside array. Array doesn't have indexOf method. List have that method.
我想知道如何在加载数组时访问列表的字段.
I would like to know how I can access to a field of the list, when I load an array.
String firstElem= l.get(0)[0];
get(0) 为您提供第一个插入的数组,而 [0] 为您提供该数组中的第一个正元素.
get(0) gives you the first inserted array and [0] gives you the first positiend element in that array.
如果您要查找数组中 A
的位置,请使用 l.get(0)
从列表中访问该数组,并遍历您获得的数组A
的位置.
If you are looking for position of A
in array, access the array from list with l.get(0)
and iterate over the array you got to get the position of A
.
评论后更新:如果你不知道索引你有
for (int i = 0; i < l.size(); i++) {
for (int j = 0; j < l.get(i).length; j++) {
if( l.get(i)[j].equalsIgnoreCase("A")){
return j;
}
}
}
注意:将其视为示例代码并添加对空值、重复项等的检查...
Note: Consider that as a example code and add checks for null's ,duplicates etc ...
这篇关于我如何访问 List 的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!