【问题标题】:List comparison and to get the Index [closed]列表比较并获取索引 [关闭]
【发布时间】:2013-10-25 11:43:23
【问题描述】:

我有 2 个对象列表,一个是 UI 对象,另一个是数据库对象,我想比较对象列表(UI 和数据库对象)并获取 UI 对象列表的索引。

List<ObjectVO> listOfVOObj = new ArrayList<ObjectVO>();
List<ObjectDB> listOfDBObj = new ArrayList<ObjectDB>();


ObjectVO{
private String regNo;
private String userId;
private String name;
...
}

ObjectDB{
private String regNo;
private String userId;
..
}

listOfVOObj:
index regNo userId name
1     123   456    name1
2     2233  567    name2 
3     2234  568    name3
4     2235  569    name4
5     2236  570    name5


listOfDBObj:
index regNo userId
1     2233  567    
2     2234  568    

我必须比较两个列表,并希望获取 listOfVOObj 中与 listOfDBObj 中的记录匹配的记录的索引。

【问题讨论】:

  • 发布一些你到目前为止尝试过的代码。
  • 你能给我们看一些你的代码吗?还是没有一行?
  • 抱歉没有正确发布问题。
  • @user2507974 没问题,否决票已删除 :) 但是您想在 regNo、userId 或两者上比较它们?如果您可以发布一些代码与您的比较,就我而言,看起来两个for loops 可以完成这项工作。
  • 谢谢 :) 我必须比较 regNo 和 userId,我不知道该怎么做。

标签: java list object indexing comparison


【解决方案1】:

从您的描述看来,这应该足够了:(在代码中我正在比较 regNo 上的对象)

List<string> indexList = new List<string>();

for (int i = 0; i < listOfVOObj.length(); i++)
{
    for (int j = 0; j < listOfDBObj.length(); j++)
    {
        if (listOfVOObj[i].regNo == listOfDBObj[j].regNo && listOfVOObj[i].userId == listOfDBObj[j].userId)
        {
            int  index = i + 1;
            indexList.Add(index);
        }
    }
}

如果您想先存储两个对象的索引,您必须像这样创建新类:

public class MyClass
{
        string indexVOObj;
        string indexDBObj;

        public MyClass(string index1, string index2)
        {
                indexVOObj = index1;
                indexDBObj = index2;
        }
}

那么你必须使用这个:

List<MyClass> indexList = new List<MyClass>();

for (int i = 0; i < listOfVOObj.length(); i++)
{
   for (int j = 0; j < listOfDBObj.length(); j++)
   {
       if (listOfVOObj[i].regNo == listOfDBObj[j].regNo && listOfVOObj[i].userId == listOfDBObj[j].userId)
       {
           int  index1 = i + 1;
           int  index2 = j + 1;
           indexList.Add(new MyClass(index1, index2));
       }
   }
}

【讨论】:

  • 感谢您的回复。
  • @user2507974 没问题干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2015-01-27
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
相关资源
最近更新 更多