Question

I have a method that returns all of Articles from database with this code:

public static List getAllArticles(){
    Session se=openSession();
    List li=se.createCriteria(Article.class).list();
    se.close();
    return li;
}

but when I want to use for-each on its result as this:

for(Article a :Boss.getAllArticles()){
          //      
   }

this error shown:

incompatible types: Object cannot converted to Article

Was it helpful?

Solution

You can use generics to make this simpler. Your getAllArticles can return a list of Article objects. It would look like this:

public static List<Article> getAllArticles(){
    Session se=openSession();
    List<Article> li= (List<Article>)(se.createCriteria(Article.class).list());
    se.close();
    return li;
}

Then you should be able to iterate over it using the loop you showed:

   for(Article a : Boss.getAllArticles()){
          //      
   }

OTHER TIPS

Use your List as generic type. then iterate your list, it does not require to cast your object.

List<Article> li=(List<Article>)se.createCriteria(Article.class).list();

Make changes as under -

return (List<Article>)li; 
and public static List<Article> getAllArticles(){}

OR iterate thru Object, simple.

Try to work out using this also.

List<Article > articleValueList = new ArrayList<Article >();
Criteria criteria = session.createCriteria(Article.class);
articleValueList = (List<Article>) criteria.list();

you can iterate this articleValueList for fetching the values from the datatbase.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top