programing

Java 동적 어레이 크기

bestcode 2022. 9. 3. 13:20
반응형

Java 동적 어레이 크기

xClass라는 클래스가 있으며 xClass 배열에 로드하고 싶기 때문에 다음과 같이 선언합니다.

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();

하지만 10개가 필요할지 모르겠어요.그 건에 대해서는 8이나 12 혹은 다른 번호가 필요할지도 모릅니다.런타임에나 알 수 있어요.배열의 요소 수를 즉시 변경할 수 있습니까?만약 그렇다면, 어떻게?

아니요, 어레이 크기를 한 번 생성하면 변경할 수 없습니다.필요 이상으로 할당하거나 크기를 늘리기 위해 재할당해야 하는 오버헤드를 감수해야 합니다.이 경우 새 데이터를 할당하고 오래된 데이터를 새 데이터로 복사해야 합니다.

int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
    oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;

이 경우 Java Collections를 사용하는 것이 좋습니다.특히 어레이를 기본적으로 랩하고 필요에 따라 어레이를 확장하기 위한 논리를 관리합니다.

List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());

으로는 「」입니다.ArrayList는 어레이에 대해 몇 가지 이유로 권장되는 솔루션입니다.우선 어레이는 가변성이 있습니다.작업을 :

class Myclass {
    private int[] items;

    public int[] getItems() {
        return items;
    }
}

발신자가 개인 데이터 구성원을 변경할 수 있기 때문에 모든 종류의 방어적 복사가 발생할 수 있습니다.이 버전을 List 버전과 비교해 보십시오.

class Myclass {
    private List<Integer> items;

    public List<Integer> getItems() {
        return Collections.unmodifiableList(items);
    }
}

in Java 배열 길이는 고정되어 있습니다.

하고 List를 할 수 .toArray (필요한 경우)method ()를 참조해 .

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class A  {

    public static void main( String [] args ) {
        // dynamically hold the instances
        List<xClass> list = new ArrayList<xClass>();

        // fill it with a random number between 0 and 100
        int elements = new Random().nextInt(100);  
        for( int i = 0 ; i < elements ; i++ ) {
            list.add( new xClass() );
        }

        // convert it to array
        xClass [] array = list.toArray( new xClass[ list.size() ] );


        System.out.println( "size of array = " + array.length );
    }
}
class xClass {}

다른 사용자가 말했듯이 기존 Java 배열의 크기를 변경할 수 없습니다.

Array List는 표준 Java가 동적 크기 배열에 가장 가까운 배열입니다.다만, ArrayList(실제로는 List 인터페이스)에는, 「array like」가 아닌 것이 있습니다.예를 들어 다음과 같습니다.

  • 하면 안 요.[ ... ]목록을 인덱싱합니다. 하다를 요.get(int) ★★★★★★★★★★★★★★★★★」set(int, E)★★★★★★★★★★★★★★★★★★.
  • "Array List" (어레이 리스트) "0" (어레이 리스트)후 20개의 ArrayList를 호출할 수 .set(15, foo).
  • ArrayList arraylist의 array array 。으로 여러 사용법을 해서 하는 예요.add,insert ★★★★★★★★★★★★★★★★★」remove★★★★★★★★★★★★★★★★★★.

어레이와 같은 것이 필요한 경우는, 독자적인 API를 설계할 필요가 있습니다(기존의 서드파티 라이브러리와 보조를 맞출 수도 있습니다).구글에서 2분짜리 '리서치'를 해도 찾을 수 없었습니다:-)

초기화에 따라 확장되는 어레이만 실제로 필요한 경우 솔루션은 다음과 같습니다.

ArrayList<T> tmp = new ArrayList<T>();
while (...) {
    tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);

요소의 수는 작성할 때 원하는 대로 설정합니다.

xClass[] mysclass = new xClass[n];

그런 다음 루프에서 요소를 초기화할 수 있습니다.이게 당신에게 필요한 거라고 추측하고 있어요.

한 후 경우 를 사용해야 .ArrayList.

Array List를 사용할 수 있습니다.

import java.util.ArrayList;
import java.util.Iterator;

...

ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());

다른 사용자가 말하듯이 java.util을 구현해야 합니다.목록.

어떤 이유로 어레이가 최종적으로 필요한 경우 다음 두 가지 작업을 수행할 수 있습니다.

  • 목록을 사용하여 myList.toArray()를 사용하여 배열로 변환합니다.

  • 특정 크기의 배열을 사용합니다.필요한 사이즈는 java.util로 변경할 수 있습니다.어레이 방식

최선의 해결책은 고객의 문제에 따라 달라집니다.

Arrays.copyOf()증가 문제를 해결하기 위한 옵션이 많이 .method는 Array length dynamically 증가 문제를 합니다.

자바 API

예, 랩하고 컬렉션 프레임워크를 사용합니다.

List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());

그런 다음 필요에 따라 List.toArray()를 사용하거나 해당 목록을 반복합니다.

대신 벡터를 사용하는 것을 추천합니다.매우 사용하기 쉽고 구현 방법이 미리 정의되어 있습니다.

import java.util.*;

Vector<Integer> v=new Vector<Integer>(5,2);

요소를 추가하려면 다음을 사용합니다.

v.addElement(int);

(5,2)에서 첫 번째 5는 벡터의 초기 크기이다.초기 크기를 초과하면 벡터가 두 자리씩 커집니다.다시 초과하면 다시 2계단씩 증가하게 됩니다.

myclass [ ]배열을 다음과 같이 선언합니다.

xClass myclass[] = new xClass[10]

필요한 XClass 요소의 수를 인수로 전달하기만 하면 됩니다.그 시점에서 당신은 얼마나 많은 것이 필요한지 알 수 있습니까?어레이에 10개의 요소가 있다고 선언하는 것은 10개의 XClass 객체를 선언하는 것이 아니라 단순히 10개의 xClass 요소를 가진 어레이를 작성하는 것입니다.

Java 어레이 사이즈는 고정되어 있습니다.다이나믹 어레이는 C++와 같이 만들 수 없습니다.

네, 이렇게 하면 돼요.

import java.util.Scanner;

public class Collection_Basic {

    private static Scanner sc;

    public static void main(String[] args) {

        Object[] obj=new Object[4];
        sc = new Scanner(System.in);


        //Storing element
        System.out.println("enter your element");
        for(int i=0;i<4;i++){
            obj[i]=sc.nextInt();
        }

        /*
         * here, size reaches with its maximum capacity so u can not store more element,
         * 
         * for storing more element we have to create new array Object with required size
         */

        Object[] tempObj=new Object[10];

        //copying old array to new Array

        int oldArraySize=obj.length;
        int i=0;
        for(;i<oldArraySize;i++){

            tempObj[i]=obj[i];
        }

        /*
         * storing new element to the end of new Array objebt
         */
        tempObj[i]=90;

        //assigning new array Object refeence to the old one

        obj=tempObj;

        for(int j=0;j<obj.length;j++){
            System.out.println("obj["+j+"] -"+obj[j]);
        }
    }


}

Array List는 원시 타입의 배열을 필요로 할 때 메모리를 많이 사용하기 때문에 IntStream을 사용하는 것이 좋습니다.int 배열을 작성하기 위한 builder()입니다(LongStream 및 DoubleStream 빌더를 사용할 수도 있습니다).

예:

Builder builder = IntStream.builder();
int arraySize = new Random().nextInt();
for(int i = 0; i<arraySize; i++ ) {
    builder.add(i);
}
int[] array = builder.build().toArray();

주의: Java 8 이후 사용 가능.

먼저 저장해야 할 양을 확보한 후 어레이를 초기화하는 것이 좋습니다.

, 다이나믹 사용할 수 .ArrayList()및 사용al.add();함수를 계속 추가하면 고정 배열로 전송할 수 있습니다.

//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList(); 
//add a certain amount of data
for(int i=0;i<x;i++)
{
  al.add("data "+i); 
}

//get size of data inside
int size = al.size(); 
//initialize String array with the size you have
String strArray[] = new String[size]; 
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
  strArray[i] = al.get(i);
}

그렇게 하는 것은 불필요한 일이지만, 그 아이디어를 보여드리기 위해ArrayList님은 다른 원시 데이터 타입과는 달리 오브젝트를 유지할 수 있어 조작이 매우 용이합니다.중간에서 삭제도 간단합니다.또, 완전히 동적인 것도 마찬가지입니다.List그리고.Stack

실행 시 크기를 변경할 수 있을지 모르겠지만 실행 시 크기를 할당할 수 있습니다.다음 코드를 사용해 보십시오.

class MyClass {
    void myFunction () {
        Scanner s = new Scanner (System.in);
        int myArray [];
        int x;

        System.out.print ("Enter the size of the array: ");
        x = s.nextInt();

        myArray = new int[x];
    }
}

그러면 어레이 크기가 실행 시 x에 입력된 것과 동일하게 할당됩니다.

다음은 Array List를 사용하지 않는 방법입니다.사용자가 크기를 지정하면 재귀에 대한 do-while 루프를 추가할 수 있습니다.

import java.util.Scanner;
    public class Dynamic {
        public static Scanner value;
        public static void main(String[]args){
            value=new Scanner(System.in);
            System.out.println("Enter the number of tests to calculate average\n");
            int limit=value.nextInt();
            int index=0;
            int [] marks=new int[limit];
            float sum,ave;
            sum=0;      
            while(index<limit)
            {
                int test=index+1;
                System.out.println("Enter the marks on test " +test);
                marks[index]=value.nextInt();
                sum+=marks[index];
                index++;
            }
            ave=sum/limit;
            System.out.println("The average is: " + ave);
        }
    }

Java 어레이의 크기는 항상 고정 길이이지만 런타임에 어레이 크기를 동적으로 늘릴 수 있는 방법이 있습니다.

이것은 가장 「사용」이면서도, 그것을 실시하기 위한 바람직한 방법입니다.

    int temp[]=new int[stck.length+1];
    for(int i=0;i<stck.length;i++)temp[i]=stck[i];
    stck=temp;

위의 코드에서는 새로운 temp[]배열을 초기화하고 있습니다.또한 for 루프를 사용하여 원래 배열의 콘텐츠(stck[])를 사용하여 temp의 콘텐츠를 초기화하고 있습니다.다시 원래 사이즈로 복사하면 새로운 사이즈 어레이를 얻을 수 있습니다.

루프를 반복하여 사용하는 어레이를 재초기화하면 CPU 오버헤드가 생성됩니다.하지만 여전히 코드로 사용하고 구현할 수 있습니다.데이터를 가변 길이의 메모리에 동적으로 저장하는 경우 Array 대신 Linked List를 사용하는 것이 좋습니다.

런타임에 어레이 크기를 늘리는 동적 스택을 기반으로 한 실시간 예제입니다.

파일명: DStack.java

public class DStack {
private int stck[];
int tos;

void Init_Stck(int size) {
    stck=new int[size];
    tos=-1;
}
int Change_Stck(int size){
    return stck[size];
}

public void push(int item){
    if(tos==stck.length-1){
        int temp[]=new int[stck.length+1];
        for(int i=0;i<stck.length;i++)temp[i]=stck[i];
        stck=temp;
        stck[++tos]=item;
    }
    else
        stck[++tos]=item;
}
public int pop(){
    if(tos<0){
        System.out.println("Stack Underflow");
        return 0;
    }
    else return stck[tos--];
}

public void display(){
    for(int x=0;x<stck.length;x++){
        System.out.print(stck[x]+" ");
    }
    System.out.println();
}

}

파일 이름:Exec.java
(메인 클래스 포함)

import java.util.*;
public class Exec {

private static Scanner in;

public static void main(String[] args) {
    in = new Scanner(System.in);
    int option,item,i=1;
    DStack obj=new DStack();
    obj.Init_Stck(1);
    do{
        System.out.println();
        System.out.println("--MENU--");
        System.out.println("1. Push a Value in The Stack");
        System.out.println("2. Pop a Value from the Stack");
        System.out.println("3. Display Stack");
        System.out.println("4. Exit");
        option=in.nextInt();
        switch(option){
        case 1:
            System.out.println("Enter the Value to be Pushed");
            item=in.nextInt();
            obj.push(item);
            break;
        case 2:
            System.out.println("Popped Item: "+obj.pop());
            obj.Change_Stck(obj.tos);
            break;
        case 3:
            System.out.println("Displaying...");
            obj.display();
            break;
        case 4:
            System.out.println("Exiting...");
            i=0;
            break;
        default:
            System.out.println("Enter a Valid Value");

        }
    }while(i==1);

}

}

이것으로 궁금증이 해결되길 바랍니다.

넌 할 수 있어

private  static Person []  addPersons(Person[] persons, Person personToAdd) {
    int currentLenght = persons.length;

    Person [] personsArrayNew = Arrays.copyOf(persons, currentLenght +1);
    personsArrayNew[currentLenght]  = personToAdd;

    return personsArrayNew;

}

언급URL : https://stackoverflow.com/questions/1647260/java-dynamic-array-sizes

반응형