How to add new elements to an array?(如何向数组中添加新元素?)
问题描述
I have the following code:
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.
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 );
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 );
这篇关于如何向数组中添加新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何向数组中添加新元素?


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01