0

I have a problem trying to read the contents in my peakperiod list. The error I have received is java.lang.object cannot be cast to java.lang.String.
Are there any possible workaround for this problem as I am using java 1.6?

Delegate.java

 List peakPeriod = new ArrayList();  
 try{
     peakPeriod = Dao.retrievePeakPeriod("2017");
 for (Iterator i=peakPeriod.iterator(); i.hasNext(); {
     System.out.println("Peak Periods:"+(String)i.next());
 }
 catch(Exception e){ System.out.println("Error:"+e);}

Dao.java

public List retrievePeakPeriod(String year) throws DataAccessException;

DaoImpl.java

public List retrievePeakPeriod(String year) throws DataAccessException {
    List list = getHibernateTemplate().find("select cal.startdate,cal.enddate from Calendar cal " +
            "where to_char(cal.startdate,'yyyy') = ?",
            new Object[] { year },
            new Type[] { Hibernate.STRING });

    return list;
}
Arjun
  • 144
  • 2
  • 14
Janos Fang
  • 13
  • 5
  • 1
    Don't use raw types. http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it. Your query returns a List. So it's quite expected that casting its element to String would fail. – JB Nizet Feb 19 '17 at 09:06
  • Thanks and understood. However, I couldn't use <> for java 1.6 but had to use arraylist to retrieve the results. – Janos Fang Feb 19 '17 at 09:19
  • Generics were introduced in Java 5, in 2004, so 13 years ago. 2 years before the first version of Java 6 came out. So yes, you definitely can use generics in Java 6. – JB Nizet Feb 19 '17 at 09:21

1 Answers1

1
System.out.println("Peak Periods:"+ i.next());

You don't have to cast it to a String - java will automatically call the toString() method, so the above is equivalent to:

System.out.println("Peak Periods:"+ i.next().toString());

If your list can have nulls, you can do something safer such as:

System.out.println("Peak Periods:"+ String.valueOf(i.next()));

Edit: This assumes that the object returned has a useful toString representation and it's what you want. Otherwise, you'd need to figure out the type (class) of (the) object that's returned and do with it what you want.

LazyCubicleMonkey
  • 1,213
  • 10
  • 17
  • Thanks for the swift reply. I have tried the 3 above solution but the result are similar. Peak Periods:[Ljava.lang.Object;@40dc76dd Peak Periods:[Ljava.lang.Object;@49ffc86f Peak Periods:[Ljava.lang.Object;@37c0155d Peak Periods:[Ljava.lang.Object;@23baa943 Peak Periods:[Ljava.lang.Object;@33be8008 – Janos Fang Feb 19 '17 at 09:20
  • @JanosFang Which shows what I'm telling you in my comment: your query returns a List, not a List. How could two fields (cal.startdate and cal.enddate) be stored in a single String? – JB Nizet Feb 19 '17 at 09:23
  • @JBNizet Thanks JBNizet for identifying the cause. It was my blunder that did not took the parameters into consideration. – Janos Fang Feb 19 '17 at 09:39