简体   繁体   English

将HashMap.keySet()转换为CharSequence []?

[英]Convert HashMap.keySet() to CharSequence[]?

I have a method in a client class that gathers data from a server, and returns a HashMap. 我在客户端类中有一个从服务器收集数据并返回HashMap的方法。 I want to list the keys in an android dialog. 我想在Android对话框中列出按键。 The android API requires that the data must be in in the form of a CharSequence[]. android API要求数据必须采用CharSequence []的形式。 So far as I can tell, there is no direct way to convert these data types. 据我所知,没有直接方法可以转换这些数据类型。 What would be the best way to accomplish this? 做到这一点的最佳方法是什么?

Here is the declaration and initialization of the hashmap and keyset: 这是哈希图和键集的声明和初始化:

Map <String, String> players = client.listPlayers();
Set<String> player_names = players.keySet();

And here is the link to the android Dialog documentation. 这是android Dialog文档的链接。

Note: CharSequence, which is able to be casted from a Set is not the same as CharSequence[] 注意:可以从Set中强制转换的CharSequence与CharSequence []不同

Any help is appreciated. 任何帮助表示赞赏。

-Sean W. 塞恩·W

CharSequence[] player_names = players.keySet().toArray(new CharSequence[0]);

This tells the method the type of the array without allocating any space for elements. 这告诉方法数组的类型,而没有为元素分配任何空间。 It will allocate a correctly-sized array for you. 它将为您分配一个正确大小的数组。

If you prefer to allocate the real array yourself: 如果您希望自己分配实数组:

CharSequence[] player_names = players.keySet().toArray(new CharSequence[players.size()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Hashmap.keySet(),foreach和remove - Hashmap.keySet(), foreach, and remove 使用HashMap.keySet作为脏副本 - Using HashMap.keySet as a dirty copy hashmap.keyset()会按照它们添加到hashmap的顺序返回键吗? - Will hashmap.keyset() return keys in the order they were added to the hashmap? HashMap.keySet()如何返回键的视图? - How can HashMap.keySet() return a view of keys? HashMap.KeySet()在Java 7中以不同顺序返回键Java 8 - HashMap.KeySet() returns keys in different order in Java 7 Java 8 HashMap.values()/ HashMap.keySet()何时按引用返回,何时按值返回? - When Does HashMap.values()/HashMap.keySet() Return By Reference And When Does It Return By Value? HashMap.values()和HashMap.keySet()如何返回值和键? - How do HashMap.values() and HashMap.keySet() return values and keys? 如何从Java Rest服务在引导表中显示Java Hashmap.keySet()? - How to display Java Hashmap.keySet() in a bootstrap table, from a java rest service? 是什么导致java.util.HashSet和HashMap.keySet()类的iterator()稍微不可预测的排序? - What causes the slightly unpredictable ordering of the iterator() for the java.util.HashSet and HashMap.keySet() classes? 将Object []从hashmap键集转换为String []? - convert Object[] from a hashmap keyset to String[]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM