我试图根据其中一个属性的值查找 ArrayList 中元素的索引,但它总是给我 -1。
//returnABClinklist method returns ABC linked list and i cannot use index of on linked list so am trying to convert it to arraylist
List<ABC> temp=new ArrayList<ABC>(someMethod.returnABClinklist());
List<XYZ> other=new ArrayList<XYZ>();
假设 ABC
有 3 个字段(rollnum
、name
、state
)和 XYZ
有 5 个字段,其中 3 个与 ABC
相同(rollnum
、name
、state
、 第二名
,dob
)。我希望它迭代一个列表,并根据其 rollnum
值相同的情况,在另一个列表中找到每个相应的元素。我的目标是填写其他相应字段(name
和 state
)。这是我尝试过的:
Iterator<ABC> itr = abcList.iterator();
while(itr.hasNext()){
ABC tempABC=itr.next();
int index = xyzList.indexOf(tempABC.rollnum()); //this always comes -1
}
问题是 indexOf()
总是返回 -1。有人可以帮助我实现吗?
实际工作片段
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class testLists {
public static void main(String[] args){
List<XYZ> temp=new ArrayList<XYZ>();
List<ABC> other=new ArrayList<ABC>();
ABC ab=new ABC();
ABC ab1=new ABC();
ab.rollnum=111;
ab.name="MAK";
other.add(ab);
ab1.rollnum=222;
ab1.name="DAK";
other.add(ab1);
XYZ abd=new XYZ();
XYZ abd1=new XYZ();
abd1.nameDB="MAK";
abd1.rollnumDB=111;
temp.add(abd1);
abd.nameDB="PONTY";
abd.rollnumDB=456;
temp.add(abd);
Iterator<XYZ> itr=temp.iterator();
while(itr.hasNext()){
XYZ tempXYZ=itr.next();
int index=other.indexOf(tempXYZ.getRollnumDB()); //this always comes -1
other.get(index) //get the data a
//add more values to the tempXYZ
});
}
}
POJO
public class ABC {
int rollnum;
String name;
String state;
public int getRollnum() {
return rollnum;
}
public void setRollnum(int rollnum) {
this.rollnum = rollnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public String getState() {
return name;
}
public void setState(String name) {
this.name = name;
}
}
注意:尝试在我的 XYZ pojo 中实现 equals 但仍然没有运气
最佳答案
indexOf
的参数是隐藏在 XYZ
对象实例中的东西,但它不是 XYZ
类型。在您的情况下,您必须迭代 XYZ
列表,从中获取 rollnum
,然后进行比较。
一般来说,我建议查看 map
。您可以使用 rollnum
作为键保存 XYZ
元素,以便 someMap.get(rollNum)
为您提供相应的 XYZ
元素。
关于java - Arraylist<ABC> 中的索引与其他 Arraylist 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415678/