简体   繁体   English

Java 1.6 arraylist对象无法转换为字符串

[英]java 1.6 arraylist object cannot cast to string

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. 我收到的错误是java.lang.object无法转换为java.lang.String。
Are there any possible workaround for this problem as I am using java 1.6? 我正在使用Java 1.6时,此问题有任何可能的解决方法吗?

Delegate.java 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 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;
}
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: 您不必将其强制转换为String-Java将自动调用toString()方法,因此上述等效于:

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. 编辑:这假定返回的对象具有有用的toString表示形式,这就是您想要的。 Otherwise, you'd need to figure out the type (class) of (the) object that's returned and do with it what you want. 否则,您需要确定返回的对象的类型(类)并根据需要进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM