如何在Java中将字符串集合转换为字符串数组

8

我正在尝试将一个字符串集合 attributeNames 传递给一个接受字符串数组的方法 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;
   }

Definition for 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中将字符串集合转换为字符串数组?有什么想法吗?


2
这可能会有所帮助 https://dev59.com/Xm855IYBdhLWcg3w_5mm - Susie
2
@MarkPeters 噢,toArray() 不也适用于 Collections(而不仅仅是 Lists)吗? - vikingsteve
学会阅读JavaDoc!你要找的是Collection API 的一部分... 最后两个方法就是你要找的。 - jahroy
@vikingsteve:不,你是对的,它确实在那里。老实说,我只是假设它不存在,因为这可以解释为什么OP错过了它(另外,集合与数组的映射不太好)。 - Mark Peters
被标记为“重复”的问题的答案都是完全针对ArrayList的。而这个问题则更一般地涉及Java集合,可能是ArrayList,也可能不是。 - Ogre Psalm33
1个回答

10

从Javadocs中的Collection中:

<T> T[] toArray(T[] a)

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

请注意,此方法接受与集合相同类型的数组;但是,Java不允许您实例化一个通用数组,因此您需要绕过它。有关更多信息,请参阅此问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接