1

I need to instantiate a list with multiple String objects. I am not allowed to manually add objects 1 by 1.

I tried multiple ways, cannot get method to accept it.

scrambleOrRemove(["TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS"]);

Method:

public static void scrambleOrRemove(List<String> list)
{
  int length = list.size()-1;
  for(int i=0;i<length;i++)
  {
    String otherword = list.get(i);
    if(scrambleWord(otherword).equals(otherword))
    {
     list.remove(i);
    }

  }

  System.out.println(list);
}
  • What is `scrambleWord`? And you need an `i--` after calling `list.remove(i)`. – Elliott Frisch Sep 25 '16 at 02:11
  • 1
    `asList()` or you can use the `addAll()` method too. See here: http://stackoverflow.com/questions/24922011/add-multiple-string-variables-to-arraylist/24922034#24922034 – markspace Sep 25 '16 at 02:34

2 Answers2

0

Call it like this:

scrambleOrRemove(
  new ArrayList<String>(
     Arrays.asList(
       "TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS"
     )
  )
);

Now that you have your solution, read the manuals and explain why this works and why it was necessary for your case.

Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
0

You can use java.util.Arrays.asList() method. So for your example -

Arrays.asList({"TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS"});

Perhaps not relevant to your example as you are removing elements from your list later but you can also look into ImmutableList of Guava for doing this in general - https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/ImmutableList.html

ImmutableList.of("TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS");
Sameer
  • 28
  • 3