7

I am trying to pass attributeNames which is a collection of string to a method setColumnNames that accepts string array.

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

I am getting this exception everytime-

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

How can I convert collection of strings to string array in Java? Any idea?

  • 2
    This may help http://stackoverflow.com/questions/4042434/convert-string-arraylist-to-string-array-in-java – Susie May 28 '13 at 20:42
  • 2
    @MarkPeters Oh, doesn't `toArray()` also work with Collections (rather than specifically Lists) ? – vikingsteve May 28 '13 at 20:46
  • Learn to read JavaDoc! What you're looking for is part of the [Collection API](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html)... The last two methods are what you're looking for. – jahroy May 28 '13 at 20:47
  • @vikingsteve: Nope, you're right, it is there. Honestly I just assumed it wasn't as that would explain why the OP missed it (plus, Sets don't map well to arrays). – Mark Peters May 28 '13 at 21:21
  • The marked "duplicate" question's answers are all *completely specific* to ArrayList. This question asks the more general question in regards to Java Collections, which *may or may not be* an ArrayList. – Ogre Psalm33 Aug 31 '17 at 21:52

1 Answers1

10

From Collection in the Javadocs:

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

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

Note that this method accepts an array of the same type as the collection; Java does not permit you to instantiate a generic array, though, so you'll need to work around it. For more info, see this question.

Community
  • 1
  • 1
Kenogu Labz
  • 1,066
  • 9
  • 20