728x90
1. 함수를 만들어서 배열을 한칸씩 확장
=> 새로운 배열 선언, 주소값을 새로 생성된 배열로 연결해줌
public class Main
{
public static int[] increaseSize(int[] arr)
{
int[] newArr = new int[arr.length + 1];//Creating a new array with space for an extra element
for(int i = 0; i < arr.length; i++)
{
newArr[i] = arr[i];//Copying the elements to the new array
}
return newArr;
}
public static void main(String[] args)
{
int[] arr = new int[5];
int counter = 0;
for(int i = 0; i <= 6; i++)
{
if(counter == arr.length)
{
arr = increaseSize(arr);
}
arr[i] = i*2;
counter += 1;
}
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
2. Arrays.CopyOf 함수를 이용
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int[] arr = new int[5];
int counter = 0;
for(int i = 0; i <= 6; i++)
{
if(counter == arr.length)
{
int[] newArr = Arrays.copyOf(arr, arr.length + 1);
arr = newArr;
}
arr[i] = i*2;
counter += 1;
}
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
3. ArrayList배열 사용
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{ //Creating a new ArrayList to hold Integer values
ArrayList<Integer> arrList = new ArrayList<Integer>();
//Adding elements 5, 10, 15 and 20 to the ArrayList
arrList.add(5);
arrList.add(10);
arrList.add(15);
arrList.add(20);
//Printing the ArrayList
System.out.println(arrList);
//Adding an element 7 at index 2. This will shift the rest of the elements one place to the right
arrList.add(2, 7);
System.out.println(arrList);
//Fetching the element at index 3
System.out.println(arrList.get(3));
//Changing the element present at index 1 to 17
arrList.set(1, 17);
System.out.println(arrList);
}
}
출처 : https://www.delftstack.com/ko/howto/java/increase-array-size-in-java/
728x90
728x90
'Programming > Java' 카테고리의 다른 글
삼항 조건 연산자 (0) | 2022.08.06 |
---|---|
동일 패키지 내의 파일 상대 경로로 가져오기 (0) | 2022.01.18 |
댓글