This is the first article. I decided to join an IT company as a member of society next year, and I am studying Java by myself. .. I'm a super beginner, so I don't think the code is helpful (it's too dirty and not good).
I looked for something like the ArrayList's ʻadd ()method using an array (such as ʻint []
).
it seems like. ..
To change the length of the array you need to make a copy of the array using System.arraycopy ()
For example, when changing from ʻint [3] to ʻint [5]
class Hairetsu {
public static void main(String args[])
{
int[] a = new int[3]; //Original
a[0] = 1;
a[1] = 2;
a[2] = 3;
int[] b = new int[5]; //Copy to
System.arraycopy( a, 0, b, 0, a.length ); //(Array a,from 0 of a,To array b,from 0 in b,Minutes of all elements of a)copy!
for ( int i = 0 ; i < b.length ; i++ ){
System.out.println( b[i] );
}
}
}
Execution result
1
2
3
0
0
It becomes the code such as. So, if you apply this and try to make something like the ʻadd ()` method in the list, ...
class HairetsuList {
static int[] list;
public static void add(int a){
int i = list.length;
int[] copy = new int[i+1]; //Create a large array with 1 element from the beginning
System.arraycopy( list , 0 , copy , 0 , i );
copy[i] = a ;
list = copy; //The length of the array is different, but there is this. ..
}
}
It looks like this, for the time being a test ...
class Test {
public static void main(String args[])
{
HairetsuList test = new HairetsuList();
test.list = new int[0];
test.add(4);
test.add(5);
test.add(3);
System.out.print("{ ");
for (int i=0 ; i < test.list.length; i++){
System.out.print( test.list[i]+" ");
}
System.out.print("}");
}
}
Execution result
{ 4 5 3 }
Aside from the childishness of the code, it was pretty good. You can use a list etc. normally. .. This time, I had to use arrays for corporate training tasks, so I tried my best to think about it, but programming is difficult. ..