将indexOf与可绘制资源列表一起使用时遇到问题。我的索引i给我的值为-1(它没有找到可绘制的资源)。
Booster booster = new Booster();
Booster booster1 = booster.findBooster(R.drawable.booster_empty);
public Booster findBooster(int boosterID) {
int[] boosterIDs = new int [] {
R.drawable.booster_empty,
R.drawable.booster_posts_1,
};
String[] names = new String[] {
"blah",
"blah"
};
String[] descriptions = new String[] {
"blah",
"blah"
};
String[] boosts = new String[] {
"blah",
"blah"
};
int i = Arrays.asList(boosterIDs).indexOf(boosterID);
Booster booster = new Booster(boosterID, names[i], descriptions[i], boosts[i]);
return booster;
}
我知道这可能非常简单,我很想念。请帮忙!
答案 0 :(得分:2)
在基本数组上调用Arrays.asList()将生成一个包含一个元素(即数组)的列表,而不是列出转换的预期数组。尝试将int[]
更改为Integer[]
。
答案 1 :(得分:0)
List.indexOf()
需要一个对象,但是你传递了一个int
,这就是为什么int是原始数据类型,而不是一个对象,这就是为什么它找不到你想要的东西< / p>
答案 2 :(得分:0)
Arrays.asList(...)方法接受所有数组元素并返回包含这些元素的List实例。在您的情况下,您添加了1个数组(对象),这是一个单独的元素。因此,当您访问任何大于0的元素时,它会抛出ArrayIndexOutOfBoundsException。请参阅下面的代码示例,输出。
//Changed the code to illustrate the best without depending on the project.
int[] boosterIDs = new int[] { 1, 2 };
//Arrays.asList() return an List object which contains only 1 element of type int[]
List<int[]> asList = Arrays.asList(boosterIDs);
for (int j = 0; j < asList.size(); j++) {
int[] item = asList.get(j);
System.out.println("Loop = " + j + "length = " + item.length + " Contents...");
for (int k = 0; k < item.length; k++) {
System.out.print(item[k] + " ");
}
System.out.println();
}
System.out.println("Printing second loop");
int[] secondBooterIds = new int[] { 3, 4 };
//Arrays.asList() return an List object which contains only 2 elements of type int[]
List<int[]> secondList = Arrays.asList(boosterIDs, secondBooterIds);
for (int j = 0; j < secondList.size(); j++) {
int[] item = secondList.get(j);
System.out.println("Loop = " + j + "length = " + item.length + " Contents...");
for (int k = 0; k < item.length; k++) {
System.out.print(item[k] + " ");
}
System.out.println();
}
Loop = 0length = 2 Contents...
1 2
Printing second loop
Loop = 0length = 2 Contents...
1 2
Loop = 1length = 2 Contents...
3 4