Java의 가변 길이 (동적) 배열
프로그램 실행을 통해 크기와 값이 변경되도록 정수 배열을 초기화하는 방법에 대해 궁금합니다. 제안 사항이 있습니까?
예 : ArrayList를 사용 합니다.
Java에서 "일반"배열은 고정 크기입니다. 크기를 지정해야하며 확장하거나 축소 할 수 없습니다. 크기를 변경하려면 새 어레이를 만들고 원하는 데이터를 복사해야합니다. 이는 비효율적이고 고통 스럽습니다.
다행히도 공통 데이터 구조를 구현하는 모든 종류의 기본 제공 클래스와 기타 유용한 도구도 있습니다. 전체 목록을 보려면 Java 6 API 를 확인 해야합니다.
한 가지주의 사항 : ArrayList는 기본 요소 (예 : 정수)가 아닌 객체 (예 : 정수) 만 보유 할 수 있습니다. 대부분의 경우 autoboxing / autounboxing 이이 문제를 자동으로 처리하지만 수행하는 작업에 따라 이상한 동작이 발생할 수 있습니다.
Java의 배열은 고정 된 크기입니다. 필요한 것은 Java에서 사용할 수있는 매우 중요한 컬렉션 중 하나 인 ArrayList입니다.
대신에
Integer[] ints = new Integer[x]
너는 사용한다
List<Integer> ints = new ArrayList<Integer>();
그런 다음 사용 목록을 변경 ints.add(y)
하고 ints.remove(z)
다른 많은 편리한 방법 사이에 적절한 Javadoc과에서 찾을 수 있습니다.
Java에서 사용할 수있는 Collections 클래스는 매우 강력하고 Java 초보자가 불필요하게 다시 작성하려고하는 많은 내장 기능을 제공하므로 공부하는 것이 좋습니다.
배열은 인스턴스화되면 고정 크기입니다. 대신 목록을 사용할 수 있습니다.
Autoboxing은 List를 배열과 유사하게 사용 가능하게 만들고, 단순히 int- 값을 넣을 수 있습니다 :
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
나는 이전의 대답이 제안에 동의 ArrayList
하기 때문에, ArrayList
입니다 하지 동적 배열 있지만 목록은 배열에 근거. 차이점은 다음을 수행 할 수 없다는 것입니다.
ArrayList list = new ArrayList(4);
list.put(3,"Test");
아직이 위치에 요소가 없기 때문에 지원 배열이 그러한 추가를 허용하더라도 IndexOutOfBoundsException이 발생합니다. 따라서 @ randy-lance에서 제안한대로 확장 가능한 사용자 지정 배열 구현을 사용해야합니다.
Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below
public class DynamicArray {
static int []increaseSizeOfArray(int []arr){
int []brr=new int[(arr.length*2)];
for (int i = 0; i < arr.length; i++) {
brr[i]=arr[i];
}
return brr;
}
public static void main(String[] args) {
int []arr=new int[5];
for (int i = 0; i < 11; i++) {
if (i<arr.length) {
arr[i]=i+100;
}
else {
arr=increaseSizeOfArray(arr);
arr[i]=i+100;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println("arr="+arr[i]);
}
}
}
출처 : 동적 배열을 만드는 방법
소규모 크기를 처리하려면 List를 사용하는 것이 좋습니다.
숫자가 너무 많으면 목록과 오토 박싱을 사용하지 마십시오 .
List <Integer> 목록
For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects. In this case, to use a estimated size would be better,
int[] array = new int[ESTIMATED_SIZE];
How about using a List
instead? For example, ArrayList<integer>
You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.
But your best option is to use IntList from jacarta commons. (here)
It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).
I answered this question and no you do not need an arraylist or any other thing this was an assignment and I completed it so yes arrays can increase in size. Here is the link How to use Java Dynamic Array and here is the link for my question which i answered Java Dynamic arrays
참고URL : https://stackoverflow.com/questions/2426671/variable-length-dynamic-arrays-in-java
'Programming' 카테고리의 다른 글
파이썬에서 단위 테스트에서 데이터 출력 (0) | 2020.08.09 |
---|---|
서블릿 필터로 요청 매개 변수 수정 (0) | 2020.08.09 |
현재 날짜 / 시간을 DD / MM / YYYY HH : MM 형식으로 가져 오려면 어떻게해야합니까? (0) | 2020.08.09 |
Linux에서 파일 끝에 줄을 추가하는 방법 (0) | 2020.08.09 |
Python의 다른 함수 내에서 호출자 함수 이름을 얻습니까? (0) | 2020.08.09 |