简体   繁体   中英

Error: The method add(java.lang.String) is undefined for the type java.lang.Object

Don't know why I'm getting this error. Working with ArrayLists and sorting words into appropriate ArrayLists by alphabetical order. If anyone can help me understand why I'm getting the error and how to fix it that would be great!

import java.util.*;

public class Sort {
    public static ArrayList<Object> sortByFirstLetter( List<String> words) {
        ArrayList<Object> bucket = new ArrayList<Object>();
        for( int i = 0; i < 26; i++ ) {
            ArrayList<String> letter = new ArrayList<String>();
            bucket.add(letter);
        }
        for( String word : words ) {
            int index = (int)(word.toLowerCase().charAt(0)) - 97; //get a number 0-25 for index; 97 is unicode for lwrcse "a"
            System.out.println(index);
            bucket.get(index).add(str);     //THIS LINE GIVES ERROR
        }
        return bucket;
    }

    public static void main(String[] args) {   
        List<String> words = Arrays.asList("alex", "andy", "kevin");
        sortByFirstLetter( words );
    }

}

It looks like bucket should be a List<List<String>> , not a List<Object> . It's not clear why you made it a List of Object in the first place.

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