我使用Arraylist并将对象插入到特定索引中。(例如,是索引为0和2的元素,但它不在索引为1的位置)我想知道我应该使用Arraylist.add(id,obj)
还是Arraylist.set(id,obj)
。我使用下面的测试if(Arraylist.get(t.imgIdx) == null)
,但它总是把Exception抛出界外。我该如何测试?
public static int GiveBackAverageID(Vector<DMatch> lista){
ArrayList<CMatch> workingList = new ArrayList<CMatch>();
for (DMatch t : lista){
if(workingList.get(t.imgIdx) == null){
workingList.add(t.imgIdx, new CMatch(t.imgIdx,t.distance,1));
}else{
CMatch pom = workingList.get(t.imgIdx);
pom.setSummaDist(pom.getSummaDist()+t.distance);
pom.setCount(pom.getCount()+1);
workingList.set(t.imgIdx, pom);
}
}
...
谢谢Csabi
如果要测试对象是否在某个位置,请使用IndexOf()
。如果对象不在列表中,则此方法返回-1。
更新
关于你的新代码:
public static int GiveBackAverageID(Vector<DMatch> lista){
ArrayList<CMatch> workingList = new ArrayList<CMatch>();
for (DMatch t : lista){
if(t.imgIdx >= workingList.size() || t.imgIdx < 0)
{
// do something with wrong indices.
}
else
{
if(workingList.get(t.imgIdx) == null){
workingList.add(t.imgIdx, new CMatch(t.imgIdx,t.distance,1));
}else{
CMatch pom = workingList.get(t.imgIdx);
pom.setSummaDist(pom.getSummaDist()+t.distance);
pom.setCount(pom.getCount()+1);
workingList.set(t.imgIdx, pom);
}
}
}
}
或者,您也可以在workingList
:中生成更多容量
public static int GiveBackAverageID(Vector<DMatch> lista){
// Creating more capacity in the constructor!
ArrayList<CMatch> workingList = new ArrayList<CMatch>(lista.size());
for (DMatch t : lista){
if(workingList.get(t.imgIdx) == null){
workingList.add(t.imgIdx, new CMatch(t.imgIdx,t.distance,1));
}else{
CMatch pom = workingList.get(t.imgIdx);
pom.setSummaDist(pom.getSummaDist()+t.distance);
pom.setCount(pom.getCount()+1);
workingList.set(t.imgIdx, pom);
}
}
}
作为更好的选择,我将使用HashTable<int,DMatch>
。
使用set在特定索引处进行替换,并在末尾添加add以添加对象,并使用index值进行添加以在位置插入对象并将其他元素向右移动(在其索引中添加一个)。
越界异常意味着您的索引值可能过大;或者数组列表没有如您所期望的那样被填充。张贴完整的异常/代码以获得完整的答案。
在尝试插入之前,您需要检查列表的大小。如果索引小于列表大小,那么您应该可以检查它是否为null,否则,您总是想添加一个新元素
我认为代码的问题在于t.imgIdx
值有时大于数组大小。
但是,当您像代码一样访问元素(应该为null)时if(workingList.get(t.imgIdx) == null)
,如果传递给get()的参数小于数组的大小,则if条件将返回布尔值。
您可以尝试下面的示例,并将不同的参数值传递给get()方法。
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(0, "5");
al.add(1, "10");
al.add(2, "15");
al.add(3, "20");
al.set(1, null);//setting the element at index 1 to NULL.
//al.remove(1);//removes the element in list so that the next element's index decreases by 1.
if(al.get(1) == null){
System.out.println("Nothing here..");//this line executes
}
else
System.out.println(al.get(1));
}
捕获异常并正确处理,它表示没有具有此索引的元素。