-2

Was pulling my hair out of this ! There are two data in text file. I trying to retrieve them out but I get below errors

##########  Error with java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.Object;  ##########
Size 1

Code

 try {
        File file = new File(filePath + "ABC.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        List list = new ArrayList();

        try {
            while ((st = br.readLine()) != null) {
                String id = st.substring(92, 100);
                try {
                    list.add(getDetail(id));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (Object[] o : (List<Object[]>) list) {
                    Details x = new Details();
                    x.setType(o[0].toString());
                     ....
                }
            }

            br.close();

        } catch (Exception ex) {
            logger.printError(Reader.class, "Error with " + ex);
        }
        logger.printInfo(Reader.class, "Size " + list.size());

    } catch (IOException ex) {
        ex.printStackTrace();
    }

Query

public List getDetail(int id){
        StringBuilder bf = new StringBuilder();
         bf.append("SELECT ");
         bf.append("'ABC', ");
                ....
        return em.createQuery(bf.toString()) .getResultList();
    }

Been stucked at here for more than 1 hour. Any help or advise would be much appreciated.

Tony
  • 2,515
  • 14
  • 38
  • 71
  • 2
    Well yes, you're trying to cast a `List` to an `Object[]`. That won't work - it's not clear why you expected it to work. To put it another way - ignoring all the *outer* list part, you're trying to write something like `Object[] o = (Object[]) getDetail(id);`. Would you expect *that* to work? (It's also very unclear why you're iterating over the list on every iteration of your while loop...) – Jon Skeet Nov 27 '17 at 09:23
  • @JonSkeet How can I solve this ? – Tony Nov 27 '17 at 09:24
  • 1
    You haven't told us what you're trying to do, so we can't tell you how to solve it - we can only tell you why you're getting the problem you're getting. (You haven't shown us how you're trying to use `o` within your loop.) – Jon Skeet Nov 27 '17 at 09:25
  • @JonSkeet edited. – Tony Nov 27 '17 at 09:28
  • The error message should be different. The cast is from `List` to `List` in the for loop. Tony, nobody can help debug or advise on a program that's so shoddily posted. – laune Nov 27 '17 at 09:32
  • Okay, so we now know that you're calling `o[0].ToString()` - but what's that meant to represent? Please read https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ and clarify your question a lot. – Jon Skeet Nov 27 '17 at 09:40
  • Can you please post your _complete_ getDetail() method? Using JPA, you should perhaps use a `TypedQuery` and avoid using `Object[]` (that's so 1980s) – Gyro Gearless Nov 27 '17 at 09:47

2 Answers2

1

Use generic types:

        List<Details> list = new ArrayList<>();

        try {
            while ((st = br.readLine()) != null) {
                String id = st.substring(92, 100);
                try {
                    list.addAll(getDetail(id)); // add all results
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            br.close();

        } catch (Exception ex) {
            logger.printError(Reader.class, "Error with " + ex);
        }

Your getDetail method should return rows converted to list of Details

public List<Details> getDetail(int id){ 
    // prepare your query
    StringBuilder bf = new StringBuilder();
    bf.append("SELECT ");
    bf.append("'ABC', ");

    // iterate over search results and convert each row into Details
    List<Details> results = new ArrayList<>();
    ResultSet rs = stmt.executeQuery(bf.toString());
    while (rs.next()) {
       results.add(toDetails(rs)); // convrt single row to Details model
    }
    return results;
}

Convert single result row to Details:

private Details toDetails(ResultSet rs){
    Details x = new Details();
    x.setType(rs.getString(0));
    ...
    return x;
}
Beri
  • 11,470
  • 4
  • 35
  • 57
  • incompatible types: List cannot be converted to Object[] in getDetail method – Tony Nov 27 '17 at 09:38
  • @Tony: Hence "do a conversion here if needed". – Jon Skeet Nov 27 '17 at 09:39
  • @JonSkeet How to convert ? – Tony Nov 27 '17 at 09:51
  • 1
    @Tony: Well, you could use `toArray()` potentially - but it feels like you're concentrating on getting a quick fix rather than taking a step back and considering *why* there's a problem and what the *best* solution is. – Jon Skeet Nov 27 '17 at 09:57
  • @JonSkeet Strange...`########## Error with java.lang.ArrayIndexOutOfBoundsException: 1 ########## Size 1` – Tony Nov 27 '17 at 10:17
  • Obj cannot converted to Obj[] – Tony Nov 27 '17 at 10:42
  • @Tony: Well you can't have *both* of those problems, as one is an exception and one is a compile-time error. You *still* haven't explained what you're trying to do - this is a real XY problem at the moment, and you should take a step back to make sure *you* know in detail what you're trying to do, then explain that in the question. – Jon Skeet Nov 27 '17 at 10:54
0

This issue seems to be related to Query API.

SO here, i would suggest to use like

public List<Object[]> getDetail(int id){
        StringBuilder bf = new StringBuilder();
         bf.append("SELECT ");
         bf.append("'ABC', ");
                ....
        return em.createQuery(bf.toString()) .getResultList(); -- getResultList returns List.
    }

And then

List<Object[]> list=new Arraylist<Object[]>();
 .....
 list.addAll(getDetail(id));  -- as we are adding collection here. 

instead of

list.add(getDetail(id));

in original code.

For more info, you can refer existing SO post

Ashish Patil
  • 4,428
  • 1
  • 15
  • 36
  • no suitable method found for add(List) method Collection.add(Object[]) is not applicable (argument mismatch; List cannot be converted to Object[]) method List.add(Object[]) is not applicable (argument mismatch; List cannot be converted to Object[]) ---- – Tony Nov 27 '17 at 09:50
  • @Tony modified code, please check. – Ashish Patil Nov 27 '17 at 09:58
  • I will get list with sizes 3. The first and second are duplicated – Tony Nov 27 '17 at 10:11
  • @Tony Ok, in that case, you need to still use `list.add(getDetail(id).get(0));` to get only single , first list. though this is not full proof solution. But this will avoid your duplicates. – Ashish Patil Nov 27 '17 at 10:15