将数据添加到列表并进行比较

时间:2017-12-04 09:32:58

标签: java list arraylist

如何加入列表并与其他列表进行比较

List list = new ArrayList();
List mList = getGroupById(date, id); // have 2 data
List tList = getSummary(date, id); // have 5 data
tList.addAll(create(tlog));

for (Rev m : (List<Rev>) mList) {
    Detail x = new Detail();
    for (Object[] s : (List<Object[]>) tList) {
        if (s[1].toString().equals(m.getMid())) {
            System.out.println("dddd " + s[1]);
        }
    }
}

查询

public List create(List<Alog> tlog) {
    List list = new ArrayList<>();
    ...

    Detail x = new Detail();
    ...
    x.setAbc(abc);
    list.add(x);

    return list;
}

public List getSummary(String date, String id)
{
    StringBuilder bf = new StringBuilder();
    bf.append("SELECT ");
    bf.append("'ABC', ");
    ...
    return em.createQuery(bf.toString())
            .setParameter("date", date, TemporalType.DATE)
            .setParameter("id", id)
            .getResultList();
}

错误

 cannot be cast to [Ljava.lang.Object;
    at com.rh.app.service.reader.SummaryReader.read(SummaryReader.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) cannot be cast to [Ljava.lang.Object;
    at com.rh.app.service.reader.SummaryReader.read(SummaryReader.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)

指向

for (Object[] s : (List<Object[]>) tList) 

1 个答案:

答案 0 :(得分:0)

Ljava.lang.Object is Object []。class的名称,java.lang.Class表示Object数组的类。

即您正在尝试转换为与您拥有的真实对象不兼容的Object []。

显然你的查询结果像往常一样是List,所以你应该尝试使用迭代器。

而不是for (Object[] s : (List<Object[]>) tList)使用:

Iterator itr = tList.iterator();
while(itr.hasNext()){
   Object[] s= (Object[]) itr.next();

   //now you have one array of Object for each row
   if (String.valueOf(s[1]).equals(m.getMid())) {
       System.out.println("dddd " + String.valueOf(s[1]));
   }
}