draca
draca

Reputation: 1399

Need help trying to declare java collections without getting warnings in eclipse

I have the following java class which works but I've tried and I can't figure out how to code it correctly to avoid the warnings in eclipse:

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class test3 {

    public static void main(String[] args) {

        LinkedHashMap<String, String> myh = new  LinkedHashMap<String, String>();
        myh.put("aa", "lettera");
        myh.put("cc", "letterc");
        myh.put("bb", "letterb");

        // this line results in warning one         
        List<String> list = new LinkedList(myh.entrySet());

        // this line results in warning two              
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
                  .compareTo(((Map.Entry) (o2)).getValue());
            }
        });
    }
}

warning 1 is: I can't figure out how to get rid of the warning in eclipse "LinkedList is a raw type. References to generic type LinkedList should be parameterized"

Warning 2 is "Type safety: Unchecked invocation sort(List, new Comparator(){}) of the generic method sort(List, Comparator) of type Collections"

Any help will be appreciated!

Upvotes: 1

Views: 99

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

To remove the raw-type; use Entry<String,String> and the diamond operator (for warning 1). Like,

List<Entry<String, String>> list = new LinkedList<>(myh.entrySet());

Then change your sort call to Compare Entry(s). Like,

Collections.sort(list, new Comparator<Entry<String, String>>() {
    public int compare(Entry<String, String> o1,
            Entry<String, String> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
});

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198103

List<Map.Entry<String, String>> list = new LinkedList<Map.Entry<String, String>>(
     myh.entrySet());
// in Java 7, you can just write new LinkedList<>(myh.entrySet())
// note that this is a List<Entry<String, String>>, not a List<String> as in the OP

Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
    public int compare(
           Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
       return o1.getValue().compareTo(o2.getValue());
    }
});

Upvotes: 2

Related Questions