views:

56

answers:

3

I want a list of things, and then I want to test the list to see if an item exists:

Here is my example snippet:

    String[] handToolArray = {"pliers", "screwdriver", "tape measure"}; 
    List<String> handToolList = new ArrayList<String>( Arrays.asList(handToolArray));

    if (handToolList.contains("pliers")){
        System.out.println("I have pliers");
    } else {
        System.out.println("I don't have pliers");
    }

In the second line, the Arrays.asList(handToolArray) generates:

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

Question: Is there a better way to create then query the list, that is succinct and does not require unchecked warnings to be suppressed?

+1  A: 

You can do it without explicitly constructing an array (arrays are still used by varargs).

List<String> handToolList = Arrays.asList("pliers", "screwdriver", "tape measure");
Matthew Flaschen
Tried that earlier, and this is what I got:The method asList(Object[]) in the type Arrays is not applicable for the arguments (String, String, String)
mb-texas
There is something wrong with your JDK setup. You should not be getting the warning in the first place.
Thilo
As noted in previous answer, I am picking up a non-JDK Arrays class. urp!
mb-texas
This works with the 'correct' import from java.util.Arrays. I like this option!
mb-texas
A: 

First of all, I do not get the type safety warning, and neither should you. What Java compiler are you using?

Arrays.asList already creates an ArrayList (backed by the original array), so if you do not need a copy, you can just do

 List<String> handToolList =  Arrays.asList(handToolArray);

Also note that something like Apache Commons Lang ArrayUtils has functions to check if an element exists in an array directly:

if (ArrayUtils.exists(handToolArray , "pliers"))
Thilo
Yes, that is a shorter piece of code (but still generates the unchecked conversion warning.)
mb-texas
As noted in previous answers, I had a bad import, and unchecked exception went away with import of java.util.Arrays
mb-texas
A: 

Note that the List interface defines the indexOf() method which you can use to check if something exist:

List<String> list = Arrays.asList(handTools);
if(list.indexOf("pliers!") != -1) {
  System.out.println("We have pliers.");
}
else {
  System.out.println("We do not have any pliers.");
}
Why would he prefer that over contains()?
Thilo