Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: convert from String to List<String>

Tags:

java

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?

like image 544
mallorn Avatar asked Jan 08 '23 06:01

mallorn


1 Answers

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>>.

like image 151
Eran Avatar answered Jan 12 '23 00:01

Eran