如何向数组添加新元素? [英] How to add new elements to an array?
本文介绍了如何向数组添加新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
这两个附加内容没有编译.这将如何正常工作?
Those two appends are not compiling. How would that work correctly?
推荐答案
无法修改数组的大小.如果你想要一个更大的数组,你必须实例化一个新的.
The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.
更好的解决方案是使用 ArrayList
可以根据需要增长.如果您需要这种形式的数组,方法 ArrayList.toArray( T[] a )
将返回您的数组.
A better solution would be to use an ArrayList
which can grow as you need it. The method ArrayList.toArray( T[] a )
gives you back your array if you need it in this form.
List<String> where = new ArrayList<String>();
where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );
如果你需要把它转换成一个简单的数组...
If you need to convert it to a simple array...
String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );
但是你用数组做的大多数事情你也可以用这个 ArrayList 做:
But most things you do with an array you can do with this ArrayList, too:
// iterate over the array
for( String oneItem : where ) {
...
}
// get specific items
where.get( 1 );
这篇关于如何向数组添加新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文