Arraylist <abc>中的索引与其他Arraylist相比较

时间:2017-04-14 16:42:25

标签: java arraylist collections

我试图根据其中一个属性的值找到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个字段(rollnumnamestate),XYZ有5个字段,其中3个与ABC相同{1}}(rollnumnamestatesecondnamedob)。我希望它迭代一个列表,并根据它们的rollnum值相同,找到另一个列表中的每个对应元素。我的目标是填写其他相应字段(namestate)。这是我试过的:

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但仍然没有运气

1 个答案:

答案 0 :(得分:1)

indexOf的参数隐藏在XYZ对象实例中,但不是XYZ类型。在您的情况下,您必须遍历XYZ列表,从中获取rollnum,然后进行比较。

一般情况下,我建议您查看Map。您可以使用XYZ作为键保存rollnum元素,以便someMap.get(rollNum)为您提供相应的XYZ元素。