Dwhitz
Dwhitz

Reputation: 1270

How to avoid : " The expression of type List needs unchecked conversion to conform to.."

I have this code :

List<Book> bookList = session.createCriteria(Book.class)
                .add(Restrictions.like("name", "%i%")).list();

But, i have a notice which say : "Type safety: The expression of type List needs unchecked conversion to conform to List"

How can i, fix my code for remove this warning?

Upvotes: 2

Views: 10884

Answers (2)

ailtonbsj
ailtonbsj

Reputation: 350

I fixed this adding an method to cast the List.

First add this method into your class:

public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
    List<T> r = new ArrayList<T>(c.size());
    for(Object o: c)
      r.add(clazz.cast(o));
    return r;
}

Then try this:

List<Book> bookList = castList(Book.class,
    session.createCriteria(Book.class).add(Restrictions.like("name", "%i%")).list());

Upvotes: 0

nano_nano
nano_nano

Reputation: 12523

add this above the line or in top of the method header:

@SuppressWarnings("unchecked")
List<Book> bookList = session.createCriteria(Book.class)
            .add(Restrictions.like("name", "%i%")).list();

or for the whole method:

@SuppressWarnings("unchecked")
public void doSomething(){

in case list() would be your own implementation you could define the result like this:

private List<Book> list(){
    return new ArrayList<Book>();
  }

then the annotation is not necessary and you have a checked conversion controlled by the compiler.

Upvotes: 1

Related Questions