Home > Java > javaTutorial > How Can I Add Elements to an Array in Java When Arrays Have a Fixed Size?

How Can I Add Elements to an Array in Java When Arrays Have a Fixed Size?

Susan Sarandon
Release: 2024-12-15 00:15:12
Original
953 people have browsed it

How Can I Add Elements to an Array in Java When Arrays Have a Fixed Size?

Modifying Arrays:

In the provided code snippet, attempts are made to append elements to an array named where. However, arrays have a fixed size, and trying to change their size like in the code snippet results in compilation errors.

Solution:

Since arrays cannot be resized, a different approach is required to add new elements. One solution is to use an ArrayList instead of an array. ArrayLists are dynamic arrays that can grow and shrink as needed.

Example Using ArrayList:

List<String> where = new ArrayList<>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
Copy after login

Converting to Array:

If you still need the data in the form of an array, you can convert the ArrayList to an array using the ArrayList.toArray() method:

String[] simpleArray = where.toArray(new String[where.size()]);
Copy after login

Benefits of ArrayList:

ArrayLists offer several advantages over arrays:

  • Dynamic size: They can grow and shrink as needed.
  • Iteration: Iterating over ArrayLists is convenient using the for each loop.
  • Element access: Elements can be accessed using the get() method.

The above is the detailed content of How Can I Add Elements to an Array in Java When Arrays Have a Fixed Size?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template