【问题标题】:How can I instantiate multiple objects into a list?如何将多个对象实例化为一个列表?
【发布时间】:2016-09-25 02:04:57
【问题描述】:

我需要用多个 String 对象实例化一个列表。我不允许手动逐个添加对象。

我尝试了多种方法,无法获得接受它的方法。

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

方法:

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);
}

【问题讨论】:

标签: java string list


【解决方案1】:

这样称呼它:

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

既然您已经有了解决方案,请阅读手册并解释为什么它有效以及为什么它对您的案例是必要的。

【讨论】:

    【解决方案2】:

    您可以使用 java.util.Arrays.asList() 方法。所以对于你的例子 -

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

    可能与您的示例无关,因为您稍后要从列表中删除元素,但您也可以查看番石榴的 ImmutableList 来做这件事 - https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/ImmutableList.html

    ImmutableList.of("TAN", "ABRACADABRA", "WHOA", "APPLE", "EGGS");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      相关资源
      最近更新 更多