我想知道,这是一种将列表转换为数组的推荐方法,因为这两种方法似乎都运行正常.
从在Java中将'ArrayList <String>转换为'String []',我看到的new String[list.size()]方式是推荐的,但我不确定为什么.
list.toArray(new String[0]);
Run Code Online (Sandbox Code Playgroud)
list.toArray(new String[list.size()]);
Run Code Online (Sandbox Code Playgroud) 我检查了以下stackoverflow源来解决我的问题:
但是,在应用顶级解决方案时,我仍然会收到错误,如下所示:
我的清单在这里定义:
List linhaInicial = new ArrayList();
Run Code Online (Sandbox Code Playgroud)
我的转换是在这里做的:
String[] convertido = linhaInicial.toArray(new String[linhaInicial.size()]);
Run Code Online (Sandbox Code Playgroud)
问题是我仍然收到以下错误:
Error:(86, 59) java: incompatible types
required: java.lang.String[]
found: java.lang.Object[]
Run Code Online (Sandbox Code Playgroud)
Object[]当它现在应该返回时,我的转换仍然以某种方式返回String[].
有解决方案吗
谢谢!
我正在使用
ArrayList<String> var1 = new ArrayList<>();
for(condition){
// Add items to var1
}
return var1.toArray(new String[]{})
Run Code Online (Sandbox Code Playgroud)
我的 IDE 建议我将最后一行更改为
return var1.toArray(String[]::new)
Run Code Online (Sandbox Code Playgroud)
这是更好的约定还是编译时或内存使用也有一些好处。
我使用以下代码将Set转换为int []
Set<Integer> common = new HashSet<Integer>();
int[] myArray = (int[]) common.toArray();
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
error: incompatible types: Object[] cannot be converted to int[]
Run Code Online (Sandbox Code Playgroud)
在没有使用for循环逐个添加元素的情况下进行转换最干净的方法是什么?谢谢!
我有一个List,我想将其转换为String [],以便我可以将其作为额外的意图传递给我.
List<String> votedBy = parseObject.getList("votedBy");
Run Code Online (Sandbox Code Playgroud)
意图逻辑:
Intent intent = new Intent(CommentActivity.this, UsersListActivity.class);
intent.putExtra(BundleConstants.KEY_LIST_TYPE, getString(R.string.voters));
intent.putExtra(BundleConstants.KEY_VOTERS_LIST, votedBy);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
我的第一个想法是将List的内容转换为String [],但是该列表是从数据库中检索的,并且其大小未知是先验的.我提出的一个建议是将votedBy List列为Parcelable.我目前无法运行代码,因此我不确定这是否有效.我该怎么办?
以下是我的代码
ArrayList<String> IdList = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)
我想从项目复制
IDList到int IdArray[].
我试着环顾一下这里和谷歌,但不幸的是什么也没发现.
这是我的代码:
class DeleteLists
{
public static void main(String[] args)
{
TokenAuth auth = new TokenAuth("xxxxx", "xxxxx");
JKippt jkippt = new JKippt(auth);
ClipList[] lists = jkippt.getLists();
for (int i = 0; i <= lists.length - 1; i++)
{
if (lists[i].isPrivate() == false);
{
{System.out.println(lists[i].getTitle);
jkippt.deleteList(lists[i].getId());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,它会输出:
DeleteLists.java:18: error: incompatible types
ClipList[] lists = jkippt.getLists();
^
required: ClipList[]
found: Iterator<ClipList>
Run Code Online (Sandbox Code Playgroud)
这很可能是一个非常基本的错误,但我在这里做错了什么?
非常感谢你提前!伊甸园.
我想知道是否可以将s 的Java转换List为Strings数组String:
我试过这个:
List<String> products = new ArrayList<String>();
//some codes..
String[] arrayCategories = (String[]) products.toArray();
Run Code Online (Sandbox Code Playgroud)
但它给了我一个例外信息:
java.lang.ClassCastException:java.lang.Object []无法强制转换为java.lang.String []