- java.util.Arrays$ArrayList cannot be cast to java.lang.String on hibernate restriction
- How to fix java.lang.classcastexception cannot be cast to in Java — cause and solution
- Cause of java.lang.ClassCastException in Java
- Common source of java.lang.ClassCastException
- How to fix java.lang.ClassCastException in Java
- ClassCastException: ArrayList cannot be cast to String
- 1 Answer 1
- Hibernate -> ArrayList cannot be cast to Set
- 2 Answers 2
java.util.Arrays$ArrayList cannot be cast to java.lang.String on hibernate restriction
I’ve been staring at this issue for too long. When executing the .list() line spring throws an exception with regards to the .add(Restrictions.in(«LocationCode», locations)) java.util.Arrays$ArrayList cannot be cast to java.lang.String. Restrictions.in is expecting (string, Object[]) no?? Can someone point out what I’m missing when passing in to the Restrictions.in??
public List getIDsByDivision(String SelectedAccountCode, List SelectedDivision, String SelectedLocation) < List IDs=null; String result="--Select--"; Session session=null; String[] locations=SelectedLocation.split(","); try < session=sessionFactory.openSession(); if(null!=SelectedAccountCode && !SelectedAccountCode.equals("--Select--") &&SelectedDivision.size()>0&&!SelectedDivision.equals("--Select--") &&locations.length>0&&!SelectedLocation.equals("--Select--")) < IDs=session.createCriteria(Customer.class) // TODO fix this to location .setProjection(Projections.distinct(Projections.property("ID"))) .add(Restrictions.eq("AcctCode", SelectedAccountCode)) .add(Restrictions.eq("Division", SelectedDivision)) .add(Restrictions.in("LocationCode", locations )) .list(); >
package ; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Customer < @Id private String ID; @Column private String Name; private String AcctCode; private String LocationCode; private String Division; private String ContactEmail; public Customer()<>public Customer(String iD, String name, String acctCode, String locationCode, String division, String contactEmail) < super(); Name = name; AcctCode = acctCode; LocationCode = locationCode; Division = division; ContactEmail=contactEmail; >public String getID() < return ID; >public void setID(String iD) < >public String getName() < return Name; >public void setName(String name) < Name = name; >public String getAcctCode() < return AcctCode; >public void setAcctCode(String acctCode) < AcctCode = acctCode; >public String getLocationCode() < return LocationCode; >public void setLocationCode(String locationCode) < LocationCode = locationCode; >public String getDivision() < return Division; >public void setDivision(String division) < Division = division; >public String getContactEmail() < return ContactEmail; >public void setContactEmail(String contactEmail) < ContactEmail = contactEmail; >>
How to fix java.lang.classcastexception cannot be cast to in Java — cause and solution
As name suggests ClassCastException in Java comes when we try to type cast an object and object is not of the type we are trying to cast into. In fact ClassCastException in Java is one of most common exception in Java along with java.lang.OutOfMemoryError and ClassNotFoundException in Java before Generics was introduced in Java 5 to avoid frequent instances of java.lang.classcastexception cannot be cast to while working with Collection classes like ArrayList and HashMap, which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException in Java by using Generics and writing type-safe parameterized classes and method, its good to know real cause of ClassCastException and How to solve it.
In this Java tutorial we will see Why java.lang.ClassCastException comes and how to resolve ClassCastException in Java. We will also see how to minimize or avoid ClassCastException in Java by using Generics, as prevention is always better than cure.
Cause of java.lang.ClassCastException in Java
In order to understand cause of ClassCastException , you need to be familiar with concept of type casting in Java. Since Java is an object oriented programming language and supports features like Inheritance and Polymorphism, a reference variable of type parent class can represent object of child class. This leads to ClassCastException if object is not of type on which you are casting it. It can be best explained with an example. Let’s see a sample code which will throw ClassCastException in Java:
Exception in thread «main» java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
If you see closely we were trying to cast an String object into an Integer object which is not correct and that’s why Java throws java.lang.classcastexception cannot be cast to error . Problems can become more difficult if all class are closely related.
Since due to polymorphism in Java an Object instance can hold any type of Object but you can only cast between same type. what makes this problem worse is that it only comes during runtime, ClassCastException doesn’t come at compile time which makes it hard to detect specially in large enterprise Java application or high frequency electronic trading system where input comes from upstream and in production various kinds of input are available.
This was frequent problem with Java Collection classes like LinkedList and HashSet in Java which holds Object type but with introduction of Generics in Java 5 solved this problem by checking type-safety during compile time. Which means you can not store Integers on LinkedList of String, from Java 5 it will result in compile time error.
Common source of java.lang.ClassCastException
1. Java Collection classes like HashMap , ArrayList , Vector or Hashtable which is not using Generics.
2. Methods which were written to take advantage of polymorphic behavior and coded on interfaces prior to Java 5 and doesn’t used parameter to provide type-safety. look for all places where you have used cast operator in Java and verify that whether that code is type-safe or not.
Here are some of the most frequently occurred ClassCastException in Java:
java.lang.classcastexception java.lang.string cannot be cast to java.lang.integer
This will come when you try to cast String object to Integer i.e.
Integer number = (Integer) stringObject;
java.lang.classcastexception java.lang.string cannot be cast to java.util.date :
This error will come when you cast String to Date in Java, since both are not related to each other, it will not possible to typecast them.
java.lang.classcastexception java.util.arraylist cannot be cast to java.lang.string
I have seen this happening a lot in beginners code based on Java Collection framework, Since ArrayList and String are not related to each other, following casting will throw this error :
String str = (String) arrayListObject;
But if you definitely wants to convert ArrayList to String, than check this post about converting collection to String in Java.
Here are couple of more examples, which is self explanatory.
java.lang.classcastexception java.util.arraylist cannot be cast to java.util.map
java.lang.classcastexception ljava.lang.object cannot be cast to ljava.lang.comparable
java.lang.classcastexception ljava.lang.object cannot be cast to ljava.lang.integer
java.lang.classcastexception ljava.lang.object cannot be cast to java.util.list
java.util.arraylist cannot be cast to java.lang.comparable
How to fix java.lang.ClassCastException in Java
Solving ClassCastException can be very easy once you understand polymorphism in Java and difference between compile time and runtime things. ClassCastException are simple like NullPointerException just look the stack-trace and go to the line number. Many of advanced Java IDE like Eclipse and Netbeans will give you hyperlink to navigate till culprit line number in Java file.
Now you know where exactly ClassCastException is coming and stack trace also told which object it was trying to cast, Now you have to find, how that type of object comes and this could take some time based upon complexity of your java application. You can also prevent ClassCastException in Java by using Generics.
Generics are designed to write type-safe code and provides compile-time checks which tends to violate type-safety. By using Generics in Collection classes and other places you can safely minimize java.lang.ClassCastException in Java.
That’s all on What is ClassCastException in Java and how to solve Exception in thread «main» java.lang.ClassCastException. I highly recommend to use Generics while using any Collection classes or class which acts as container e.g. ThreadLocal in Java. Also write your own classes and method to take advantage of Generics to provide type-safety as shown in this example of How to write parameterized class. It’s also a good idea to refresh your knowledge on type-casting in Java.
ClassCastException: ArrayList cannot be cast to String
Why are you not using generics on both sides of your declarations? Why are your variable names non-helpful?
You need to functionally decompose this. Name things in an orthogonal fashion (as mentioned above), put some comments in where things aren’t obvious and be consistent with your usage of generics. At the moment, three loops deep, this code just makes no sense. If you make it readable, the answer WILL jump out at you.
Couldn’t agree more with Hovercraft & Jeff. This code is a mess! If you just re-write it with an attempt to make it readable, your errors will become obvious. I’ve probably mis-read your code a half-dozen times trying to compose an answer. That’s a bad sign for code that SHOULD be very simple.
1 Answer 1
You have a problem with your parentheses.
You want to call get(i) and get(k) on your ArrayList , then cast that to a String .
Your code casts the result of l.get(i) to a String , then tries to call get(k) on it.
. Actually, I can barely determine what your code does, because it is so difficult to read in its current state.
The following should work and also make your code much easier to follow:
ArrayList tempList = (ArrayList) l.get(i); String tail = (String) tempList.get(k); l4.add(re.get(j) + " " + tail;
One thing that would really help would be to ensure that list l is a list of string lists . Then you wouldn’t have to cast at all. You could achive that by using the following declaration (if at all possible):
List> listL = new ArrayList>();
Here are some suggestions of how you could re-write the above and make it much easier to follow:
public static List produitCart(List listOfLists) < ListreturnList = listOfLists.get(0); for (int i = 1; i < listOfLists.size(); i++) < ListlistFour = new ArrayList(); for (int j = 0; j < returnList.size(); j++) < ArrayListtempList = listOfLists.get(i); for (int k = 0; k < tempList.size(); k++) < listFour.add(returnList.get(j) + " " + tempList.get(k)); >> returnList = new ArrayList(); for (int m = 0; m < listFour.size(); m++) < returnList.add(listFour.get(m)); >> return returnList; >
Hibernate -> ArrayList cannot be cast to Set
I have a Java EE application and I use Hibernate. The domain objects, I changed the List / ArrayList to Set / HashSet, because it is better to use Sets. But in my Dao implementation I run into a problem:
public Set getAllPersons() < SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session sess = sessionFactory.getCurrentSession(); Transaction tx = sess.beginTransaction(); @SuppressWarnings("unchecked") Setitems = (Set) sess.createQuery("from Item").list(); tx.commit(); return items; >
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Set
Are you sure that you know what the difference between a set and a list is? Because in no way is it ‘better’ to use a Set. You use Sets whenever you want a single instance of an object in your collection, whereas you can have multiple instances of the same object in a list.
2 Answers 2
List list = sess.createQuery("from Item").list(); Set items = new HashSet(list);
sess.createQuery(«from Item»).list(); will return a array list of resulting items, if you need it in Set you can make it as shown in code
«rebuild the database which might not be an option» — This makes no sense, Query.list() always returns a List : docs.jboss.org/hibernate/stable/core/javadoc/org/hibernate/…
The domain objects, I changed the List / ArrayList to Set / HashSet, because it is better to use Sets.
It’s not «better» to use Set , it depends entirely on what you need. But anyway, the collection type you use in your domain objects and the return type of Query#list() are two unrelated things.
Personally, I can’t say that I see much value in converting the result of a query into a Set (apart from eating more memory), unless you explicitly want to remove duplicates from query results of course (but in that case, I would challenge the mappings).
Now, if you insist, the various Set implementations have a constructor that takes a Collection (and the question is essentially a duplicate of Easiest way to convert a List to a Set? — Java).