【问题标题】:How to convert collection of strings to string array in java [duplicate]如何在java中将字符串集合转换为字符串数组[重复]
【发布时间】:2013-05-23 23:00:28
【问题描述】:

我正在尝试将attributeNames(这是一个collection of string)传递给一个接受string array 的方法setColumnNames

public Map<String, String> getAttributes(String rowKey, Collection<String> attributeNames, String columnFamily) {

    try {

        SliceQuery<String, String, String> query = HFactory.createSliceQuery(keyspace, StringSerializer.get(), StringSerializer.get(), StringSerializer.get()).
                setKey(rowKey).setColumnFamily(columnFamily).setColumnNames(attributeNames);

    } catch (HectorException e) {
        LOG.error("Exception in CassandraHectorClient::getAttributes " +e+ ", RowKey = " +rowKey+ ", Attribute Names = " +attributeNames);
    }

    return null;
   }

setColumnNames 的定义

SliceQuery<K, N, V> setColumnNames(N... columnNames);

我每次都会遇到这个异常-

The method setColumnNames(String...) in the type SliceQuery<String,String,String> is not applicable for the arguments (Collection<String>)

如何在 Java 中将字符串集合转换为字符串数组?有什么想法吗?

【问题讨论】:

  • @MarkPeters 哦,toArray() 不也适用于集合(而不是专门的列表)吗?
  • 学习阅读JavaDoc!你要找的是Collection API的一部分...最后两种方法就是你要找的。​​span>
  • @vikingsteve:不,你是对的,它就在那里。老实说,我只是认为这不能解释为什么 OP 错过了它(另外,集合不能很好地映射到数组)。
  • 标记的“重复”问题的答案都是完全特定于 ArrayList。这个问题提出了关于 Java 集合的更一般的问题,它可能是也可能不是一个 ArrayList。

标签: java string collections


【解决方案1】:

来自 Javadocs 中的 Collection

&lt;T&gt; T[] toArray(T[] a)

返回一个包含此集合中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。如果集合适合指定的数组,则在其中返回。否则,将使用指定数组的运行时类型和此集合的大小分配一个新数组。

请注意,此方法接受与集合相同类型的数组;但是,Java 不允许您实例化泛型数组,因此您需要解决它。欲了解更多信息,see this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2023-03-19
    • 2021-01-06
    相关资源
    最近更新 更多