This site requires JavaScript, please enable it in your browser!
Greenfoot back
Belinus
Belinus wrote ...

2021/1/25

Resize a array

Belinus Belinus

2021/1/25

#
Hi, i want to resize a array-How?
danpost danpost

2021/1/25

#
Belinus wrote...
i want to resize a array-How?
Once created, an array's size cannot be changed. Options include copying the contents into a new array of wanted size or using an ArrayList object, whose size can change, instead of a simple array.
Belinus Belinus

2021/1/25

#
Sorry, How? Could you do an example?
danpost danpost

2021/1/25

#
Belinus wrote...
Sorry, How? Could you do an example?
(A) Creating a new array:
1
2
3
4
5
6
7
8
9
// current array
char[] array = new char[] { "a", "b", "c" };
 
// adding "d"
char[] temp = array;
array = new char[temp.length+1];
int i=0;
for (;i<temp.length; i++) array[i] = temp[i];
temp[i] = "d";
{B} Using an ArrayList object:
1
2
3
4
5
6
7
// import
import java.util.ArrayList;
 
// creating an ArrayList and adding to it
ArrayList<Character> arrayList = new ArrayList<Character>();
arrayList.add('a');
arrayList.add('b');
The list can be of any Object type (primitive types prohibited). A primitive representation of the type can be used when adding them as they will be converted to be of the Object type. That is, in this, case, you need not use new Character('a') to add 'a' to the list. Refer to the java.util.ArrayList API to see what other methods are available for ArrayList objects.
You need to login to post a reply.