I am facing some problem when converting list to List
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
logger.info("in getContentDes ");
List<?> ls = ho.getResultListByLimit(sql,limit);
contentDes_ls = (List<ContentDes>)ls;
logger.info(" size of content "+contentDes_ls.size());
for (ContentDes contentDes : contentDes_ls) {
logger.info(contentDes.getPricetag());
logger.info(contentDes.getPrv());
}
Its worked fine when I get the size of List<SomeClass> but when I
access the getter and setter of SomeClass I got exception
Output:
size of content 2
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.SomeClass]
SomeClass is not mentioned anywhere in your code, so I assume you mean ContentDes.
It appears your list doesn't contain ContentDes instances. The Exception indicates the items are instead of type Object[]. This causes a ClassCastException when you try to iterate over the items as ContentDes.
Related
I define a general List which can add any type elements, define as:List<List<Object>> rows = new ArrayList<>(); but when I get a list from my service layer, the compile process would throw a incompatible types exception, codes sample as below:
List<List<Object>> rows = new ArrayList<>();
List<ProductEntity> result = searchResponse.getProducts();
rows.add(result);
the exception is: incompatible types: java.util.List<com.shopee.data.webapispec.brandseller.entity.product.ProductEntity> cannot be converted to java.util.List<java.lang.Object> when I run the command "mvn clean install", anyone knows how to handle it?
ProductEntity is a sub class of Object. However List<ProductEntity> is not a subclass of List<Object>.
You need to have List<List<? extends Object>> rows = new ArrayList<>(); to make this work.
See here for details on Generics and Object Hierarchies
In a function, i am reading a set of json's from a table & assigning it to a List. This function then returns this list.
public List<JSONObject> getJsons(){
SQLQuery query = sessionFactory.openSession().
createSQLQuery("select json from JSONTable");
List<JSONObject> jsonList = (List<JSONObject>)query.list();
return jsonList;
}
Now I thought that an error would come up when i cast the result of query, i.e List(Object) to List(JSONObject) because we can't cast an Object to a JSONObject. Assuming it works in a similar way..
But this fails when i actually use the result of this function and gives the expected casting error, as shown below
jsonList here is the result of above function...
for(JSONObject json : jsonList){
...
}
If it were a single object it would have failed at the point of casting itself..why not in this case?
I wrote this code to set the a jTable to a model to suit the data that would be returned from my query. I am not sure why this is happening but I do have an example of the same code in use and it works perfectly.
Note: the query calls records from a table that is linked to another table.
Note: Some may say this is a duplicate question but I feel not becuase Ilooked at that question and non of the solutions helped me, I tried using the iterator instead but same error occurs.
Any suggestions.
This is the code
public void createModelsAndEquipmentTableModel(){
Query query = FinancialDBPUEntityManager.createQuery("SELECT t FROM Stocktbl t WHERE t.chemical = FALSE");
List<Object[]> results = query.getResultList();
String headings[] = {"Product ID", "Product Name", "Number In Stock", "Number Needs Replacing"};
Object data[][] = new Object[results.size()][headings.length];
int index = 0;
for(Object[] obj: results){// error occurs here.
data[index++] = obj;
}
DefaultTableModel model = new DefaultTableModel(data, headings);
tblquipment.setModel(model);
}
This is the Relevant portion of the stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: GUIPac.Stocktbl cannot be cast to [Ljava.lang.Object;
at GUIPac.ViewStockInfo.createChemicalsTableModel(ViewStockInfo.java:53)
at GUIPac.ViewStockInfo.<init>(ViewStockInfo.java:30)
The query "SELECT t FROM Stocktbl t WHERE t.chemical = FALSE" will return Stocktbl objects.
When iterating over the ResultList this causes ClassCastExceptions.
I would recommend to use this createQuery-Method:
TypedQuery<Stocktbl> query = FinancialDBPUEntityManager.createQuery("SELECT t FROM Stocktbl t WHERE t.chemical = FALSE", Stocktbl.class);
and then resolve all compiler warnings and errors.
If you need an Object Array, you will have to produce it manually, when using JPA. Here is a pseudo-code for creating these Object Arrays:
for(Stocktbl stock : results){// no error occurs here anymore.
Object[] obj = new Object[] {stock.ProductId, stock.ProductName, stock.NumberInStock, stock.numberNeedsReplacing};
data[index++] = obj;
}
please change field names of Stocktbl stock to fit to your Stocktbl class
The getResultList()- method get back a List of List<Stocktbl> not of Object[].
In runtime there is no generic. But when you iterate over it the cast fails.
I want to read from database a pdf, which stores as BLOB and I want to get List<bytes[]>
session.beginTransaction();
final Criteria criteria = session.createCriteria(MyClass.class);
criteria.add(Restrictions.eq("id",id));
final ProjectionList projectionList = Projections.projectionList().add(
Projections.property("bdoc"));
criteria.setProjection(projectionList);
List<Object[]> list = criteria.list();
List<byte[]> listBytes = new ArrayList<byte[]>();
for (Object[] item : list) {
listBytes.add((byte[]) item[0]);
}
session.getTransaction().commit();
But I get an error in this line for (Object[] item : list) {
[ERROR] [B cannot be cast to [Ljava.lang.Object;
I've debugged and I do read data from database: my List<Object[]> list = criteria.list() is not empty.
But I can not convert from List<Object[]> to List<bytes[]>. What am I doing wrong? Help me please to resolve my problem.
B cannot be cast to [Ljava.lang.Object;
Means you are indeed getting bytearray and you are trying to convert it into Object array.
This problem is caused because Criteria.list() returns a raw List. As a result, you are able to write code that causes a ClassCastException. With a properly typed list, the compiler would prevent this.
As explained in the other answer, the text [B cannot be cast to [Ljava.lang.Object means that a byte[] is being cast to an Object[], which is not allowed.
This means that your list contains byte[] objects and you should declare it as such:
List<byte[]> list = criteria.list();
In addition, the contents of your for-loop now look incorrect:
listBytes.add((byte[]) item[0]);
Since item is now a byte[], it's not correct to cast a byte to a byte[]. Perhaps you need to remove the array index [0].
java.lang.UnsupportedOperationException: This operation is not supported on Query Results
at org.datanucleus.store.query.AbstractQueryResult.contains(AbstractQueryResult.java:250)
at java.util.AbstractCollection.retainAll(AbstractCollection.java:369)
at namespace.MyServlet.doGet(MyServlet.java:101)
I'm attempting to take one list I retrieved from a datastore query, and keep only the results which are also in a list I retrieved from a list of keys. Both my lists are populated as expected, but I can't seem to user retainAll on either one of them.
// List<Data> listOne = new ArrayList(query.execute(theQuery));
// DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
// List<Data> listTwo = new ArrayList(ds.get(keys).values());
// listOne.retainAll(listTwo);
EDIT
Ok, in an attempt to simplify, since this is apparently multiple problems in one, I have stopped using the low level API for datastore and instead of am just pulling one by one with a loop.
List<MyClass> test = (List<MyClass>) query.execute();
List<MyClass> test2 = new ArrayList<MyClass>();
for (String key : favorites) {
test2.add(pm.getObjectById(MyClass.class, key));
}
log.info(test.toString());
test.retainAll(test2);
The above works. It doesn't throw the exception. The below does throw the exception. The only difference is the log.info. I'm stumped.
List<MyClass> test = (List<MyClass>) query.execute();
List<MyClass> test2 = new ArrayList<MyClass>();
for (String key : favorites) {
test2.add(pm.getObjectById(MyClass.class, key));
}
test.retainAll(test2);
It will not let me do new ArrayList() on the query result since it returns an array of objects.
You however need to put them in a new ArrayList(). The returned List implementation apparently doesn't support retainAll(). That's what the exception is telling you.
A "plain" ArrayList supports it. If passing through the ArrayList constructor is not possible due to difference in generic type, then you'll need to manually loop over it and cast each item before adding.
List<Data> listTwo = new ArrayList<Data>();
for (Object object : ds.get(keys).values()) {
listTwo.add((Data) object);
}
listOne.retainAll(listTwo);
Update: as per your update, the entities are apparently lazily loaded/filled. Most ORM's (DataNucleus is one) may indeed do that. As I don't use DataNucleus, I can't go in detail how to fix that in a "nice" way. But you at least now know the root cause of the problem and it can be solved the same way as above. Fill the list test in a loop as well.
If the type of collection you use for your "list of keys" does not support retainAll that exception will be thrown. Which type are you using?
TIP: you don't need to iterate to fill listTwo.
just do:
listTwo.addAll(ds.get(keys).values())