Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

java - 如何将新元素添加到数组?(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?

(那将如何正常工作?)

  ask by Pentium10 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(更好的解决方案是使用ArrayList ,它可以根据需要增长。)

The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.

(如果您需要这种形式的数组,则ArrayList.toArray( T[] a )将为您提供数组。)

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:

(但是,使用数组执行的大多数操作也可以使用此ArrayList执行:)

// iterate over the array
for( String oneItem : where ) {
    ...
}

// get specific items
where.get( 1 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...