0

I am currently getting an error requesting that certain identifiers are expected as I try to translate this C# code:

public static List<string> stopWords = new List<string> {"ON","OF","THE","AN","A" };

current faulty Java code:

public static List<String> stopWords = new ArrayList<String {"ON","OF","THE","AN","A" };
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Rapharel
  • 33
  • 5
  • If you want to check if a word is a "stopWord", you'd likely be better off using a `Set`, because that'll perform better when calling `stopWords.contains(word)`. – Andreas Aug 20 '15 at 16:19

3 Answers3

4

You could use

List<String> stopWords = new ArrayList<>(Arrays.asList("ON","OF","THE","AN","A" ));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • You don't have to wrap the list in an `ArrayList` if the list won't be updated. Given the name `stopWords`, that is very likely here. – Andreas Aug 20 '15 at 16:17
  • @Andreas based on the OPs (now deleted) comment, seemed he wanted to add to the list so removed the 2nd option.... – Reimeus Aug 20 '15 at 17:04
2

An alternative:

List<String> stopWords = new ArrayList<String>() {{
    add("ON");
    add("OF");
    add("THE");
    add("AN");
    add("A");
}};
1218985
  • 7,531
  • 2
  • 25
  • 31
  • nice trick, it is creating anonymous class which extends ArrayList, and it defines initialization block where adds all elements to list. it might not be a best answer, but it is definitelly nice trick – user902383 Aug 20 '15 at 16:39
  • This is an abuse of anonymous inner classes - the accepted answer is much clearer. – Dave Doknjas Aug 20 '15 at 17:06
0

Add the words you want to put in a list to an array and add the array-elements using a for-loop:

  List<String> stopWords = new ArrayList<String>();
  String[] words = new String[] {
          "ON","OF","THE","AN","A"
  };
  for(String s : words) {
      stopWords.add(s);
  }
Nicolas
  • 131
  • 2