Type of mismatch: convert from string to list <String>

I mean the algorithm of my school class program, but also the difficulties in some of the basics, I think ...

here is my problem code:

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 String Element Type to List" How to properly getSortedByAnQty () initialize?

+4
source share
2 answers

an.getSortedByAnQty()returns a List<String>. When you iterate over this list, you get separate lines, so the extended loop should have a variable String:

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

If the method mainshould remain as it is, you must change getSortedByAnQtyto return List<List<String>>.

+9
source
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));
}
0
source

Source: https://habr.com/ru/post/1614253/


All Articles