Search code examples
javaobjectcastingjava.util.date

convert object into date


I get an ArrayList of Object[] from a database and I want to convert the java.sql.Date stored in an object into a java.util.Date (in order to use it in jfreechart): my code is as follows:

fills up the Array of object with data from MySQL

 ArrayList<Object[]> mydata=new ArrayList<>(); 
 mydata=sqlGetter.getMdbObjectList(sqlString, null);


for(Object[] myobject : mydata){
        if (myobject[1].getClass()==java.sql.Date.class){
           java.util.Date mydate=null;
           mydate = Date ( myobject[1]);  
        } 
}

Netbeans return an error: "Java incompatible types: Object cannot be converted to Date"

While I understand the idea, I would have expected to be able to cast the object into a Date after having checked that it is indeed of the right class.

I'm starting java, so please any helps on the obvious mistake that I must be doing would be useful.


Solution

  • You are missing a cast. Additionally, you'd be better off using the instanceof operator:

    for(Object[] myobject : mydata){
        // Note that java.sql.Date extends java.util.Date
        if (myobject[1] instanceof java.util.Date) {
            java.util.Date mydate = (java.util.Date) myobject[1];
        }
    }