4

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?

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

unfortunately I can not change the Main{} ;)
@mallorn In that case, change getSortedByAnQty to return a List<List<String>> (i.e. a list of lists).
0
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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.