且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何向数组添加新元素?

更新时间:2023-09-20 12:28:10

无法修改数组的大小.如果你想要一个更大的数组,你必须实例化一个新的.

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