mallorn
mallorn

Reputation: 815

Type mismatch: convert from String to List<String>

I have in mind the algorithm of my school-class program, but also difficulty in some basics I guess...

here is my code with the problem:

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) throws FileNotFoundException {
    String allWords = System.getProperty("user.home") + "/allwords.txt";
    Anagrams an = new Anagrams(allWords);
    for(List<String> wlist : an.getSortedByAnQty()) {
      //[..............];
    }
    }
}

public class Anagrams {

    List<String> myList = new ArrayList<String>();

    public List<String> getSortedByAnQty() {
        myList.add("aaa");
        return myList;
    }
}

I get "Type mismatch: cannot convert from element type String to List" How should initialise getSortedByAnQty() right?

Upvotes: 4

Views: 8295

Answers (2)

arjun99
arjun99

Reputation: 358

char[] cArray = "MYString".toCharArray();
convert the string to an array as above and then iterate over the character array to form a list of String as below

List<String> list = new ArrayList<String>(cArray.length);

for(char c : cArray){
    list.add(String.valueOf(c));
}

Upvotes: 0

Eran
Eran

Reputation: 393781

an.getSortedByAnQty() returns a List<String>. When you iterate over that List, you get the individual Strings, so the enhanced for loop should have a String variable :

for(String str : an.getSortedByAnQty()) {
  //[..............];
}

If the main method should remain as is, you should change getSortedByAnQty to return a List<List<String>>.

Upvotes: 9

Related Questions