user1097772
user1097772

Reputation: 3549

Type safety: The expression of type List needs unchecked conversion to conform to Collection<? extends Object>

I'm using set for defining allowed keys for some action. Eclipse shows this warning:

 Type safety: The expression of type List needs unchecked conversion
 to conform to Collection<? extends Object>


I googled a bit and found same message in slightly different cases but its probably similar problem.
Is any chance get rid of this warning other way then

 @SuppressWarnings("unchecked")

Is good idea to use

@SuppressWarnings("unchecked") 

in this case?

Here is my code:

  public static final String KEY_A = "A_VALUE";
  public static final String KEY_B = "B_VALUE";

  public static final Set<?> allowedKeys =  new HashSet<Object>(Arrays.asList(new String[] {KEY_A, KEY_B}));

Upvotes: 2

Views: 5142

Answers (3)

ArifMustafa
ArifMustafa

Reputation: 4965

Try to understand the problem using source code and get rid of type unchecked conversion warnings,

private static Vector<Vector<String>> tableVectorData;
private static Vector<String> rowData = new Vector<String>();

for adding element -

rowData.clear();
rowData.addElement((strings[0])[0][0]);
rowData.addElement((strings[0])[1][0]);
tableVectorData.addElement(rowData);

for retrieving element -

model = (DefaultTableModel) table.getModel();
rowCount = tableVectorData.size();
int i = 0;
while(i < rowCount) {
    Vector<String> row = tableVectorData.get(i++);//here the type check warning will occur
    model.setRowCount(model.getRowCount()+1);
    System.out.println(row);
    model.setValueAt(row.get(0), model.getRowCount()-1, 0);
    model.setValueAt(row.get(1), model.getRowCount()-1, 1);
}

or using Iterator<Vector<String>> -

Iterator<Vector<String>> rows = tableVectorData.iterator();//here the type check warning will occur
boolean flag = false;

checkValue:
while(rows.hasNext()) {
    Vector<String> vect = rows.next();
    if(vect.contains(value)) {
        flag = true;
        break checkValue;
    }
}

Hope these will provide you a way to deal with these expression type check warnings, thanks.

Upvotes: 0

user1097772
user1097772

Reputation: 3549

Eclipse did the mess:
Wrong:

import edu.emory.mathcs.backport.java.util.Arrays;

Correct:

import jave.util.Arrays;


So code is ok both versions Set<?> and Set<String>. Eclipse just auto imported bad class.

Upvotes: 5

Nghia
Nghia

Reputation: 188

The Set<?> or Set<Object> should only be used in case you must make it works with existing code. Otherwise, trying to make a specific type instead.

If you are sure that the set contains only String element, Set<String> is the best choice.

Upvotes: 3

Related Questions