简体   繁体   中英

error in sort a linked list alphabetically

I have LinkedList of Strings in which I insert a lot of words. I want to sort the list alphabetically.

I searched the Internet and found Collections.sort(list); but when I tried it I got an error. This is the code:

import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {
    public static void main(String[] args) {

     LinkedList<String> s=new LinkedList<String>();

        s.insert("cat");
        s.insert("apple");
        s.insert("desk");
        s.insert("bed");
        s.insert("zebra");
        s.insert("floor");

        Collections.sort(s);
    }
}

You haven't imported LinkedList and LinkedList doesn't have an insert method. Try this:

import java.util.Collections;
import java.util.LinkedList;

public class Test {
    public static void main(String[] args) {

     LinkedList<String> s=new LinkedList<String>();

        s.add("cat");
        s.add("apple");
        s.add("desk");
        s.add("bed");
        s.add("zebra");
        s.add("floor");

        Collections.sort(s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM