Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics : Unchecked cast from List<capture#10-of ?> to List<Object>

I have a warning : Type safety: Unchecked cast from List < capture#10-of ?> to List < Object>

There is the call, stock.getListDVD().getListDVD() is an ArrayList<DVD>

jTablePanier=new JTableUt(stock.getListDVD().getListDVD(), DVD.class);

So i know the class it's a DVD.class

private ModelJTableUt model;    
public JTableUt(List<?> list, Class<?> classGen)
{               
    model=new ModelJTableUt((List<Object>) list, classGen); // <-- This line cause the warning, i convert List<?> to List<Object>
}

public ModelJTableUt(List<Object> list, Class<?> classGen) {

How can i resolve this warning without using

@SuppressWarning("unchecked")

Thanks a lot for your help. It save me many hours. The solution is

 public JTableUt(List<? extends Object> list, Class<?> classGen){
    model=new ModelJTableUt(list, classGen);
 }

 List<Object> list;
 public ModelJTableUt(List<? extends Object> list2, Class<?> classGen) 
 {
     list = new ArrayList<Object>();
 //I construct a new List of Object.    
     for (Object elem: list2)
     {
         list.add(elem);
     }
 }
like image 520
user2338702 Avatar asked May 01 '13 08:05

user2338702


1 Answers

Change List<?> list to List<? extends Object> in :

public JTableUt(List<?> list, Class<?> classGen)

From Java Generics tutorial :

It's important to note that List <Object> and List<?> are not the same. You can insert an Object, or any subtype of Object, into a List<Object>. But you can only insert null into a List<?>.

like image 107
Salah Eddine Taouririt Avatar answered Oct 21 '22 08:10

Salah Eddine Taouririt