Programing

Java 배열에 항목을 동적으로 추가하려면 어떻게해야합니까?

lottogame 2020. 10. 9. 08:41
반응형

Java 배열에 항목을 동적으로 추가하려면 어떻게해야합니까?


PHP에서는 다음과 같이 배열에 요소를 동적으로 추가 할 수 있습니다.

$x = new Array();
$x[] = 1;
$x[] = 2;

그 후에는 다음 $x과 같은 배열이 {1,2}됩니다..

Java에서 비슷한 작업을 수행 할 수있는 방법이 있습니까?


java.util.LinkedList 또는 java.util.ArrayList를 살펴보십시오.

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);

Java의 배열은 크기가 고정되어 있으므로 PHP에서 할 수있는 것처럼 "끝에 무언가를 추가"할 수 없습니다.

PHP 동작과 약간 비슷합니다.

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

그런 다음 다음과 같이 작성할 수 있습니다.

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

그러나이 체계는 매번 전체 배열의 복사본을 만들기 때문에 큰 배열의 경우 매우 비효율적입니다 . (실제로 이전 배열이 동일하게 유지되기 때문에 PHP와 완전히 동일하지는 않습니다.)

PHP 배열은 실제로 "최대 키"가 추가 된 Java HashMap과 매우 동일하므로 다음에 사용할 키와 이상한 반복 순서 (및 정수 키와 일부 문자열 간의 이상한 등가 관계)를 알 수 있습니다. 그러나 간단한 색인 컬렉션의 경우 다른 응답자가 제안한 것처럼 Java의 List를 사용하는 것이 좋습니다.

ListInteger의 모든 int를 래핑하는 오버 헤드로 인해 사용을 피하려면 내부 배열을 사용하지만 내부 배열이 가득 찬 경우에만 모든 변경 사항에 대해 복사하지 않는 기본 유형에 대한 컬렉션의 재 구현을 사용하는 것이 좋습니다. ArrayList처럼). (빠르게 봤던 한 가지 예는 이 IntList 클래스 입니다.)

구아바 포함 같은 래퍼 만드는 방법 에서 Ints.asList, Longs.asList


Apache Commons에는 새 배열 끝에 요소를 추가 하는 ArrayUtils 구현이 있습니다.

/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)

저는이 질문을 웹에서 자주 보았고 제 생각에는 평판이 좋은 많은 사람들이이 질문에 적절하게 대답하지 않았습니다. 그래서 여기에 제 답을 표현하고 싶습니다.

먼저 사이 차이 가 있음을 고려해야 합니다.arrayarraylist

질문 요소를 추가하기위한 요청 어레이에하지의 ArrayList


대답은 아주 간단합니다. 3 단계로 진행할 수 있습니다.

  1. 배열을 배열 목록으로 변환
  2. arrayList에 요소 추가
  3. 새 arrayList를 배열로 다시 변환

여기에 간단한 그림이 있습니다. 여기에 이미지 설명 입력

마지막으로 코드는 다음과 같습니다.

1 단계:

public List<String> convertArrayToList(String[] array){
        List<String> stringList = new ArrayList<String>(Arrays.asList(array));
        return stringList;
    }

2 단계:

public  List<String> addToList(String element,List<String> list){

            list.add(element);
            return list;
    }

3 단계 :

public String[] convertListToArray(List<String> list){
           String[] ins = (String[])list.toArray(new String[list.size()]);
           return ins;
    } 

4 단계

public String[] addNewItemToArray(String element,String [] array){
        List<String> list = convertArrayToList(array);
        list= addToList(element,list);
        return  convertListToArray(list);
}

ArrayList를 사용한 다음 toArray()메서드 를 사용할 수 있습니다 . 그러나 수행중인 작업에 따라 어레이가 전혀 필요하지 않을 수도 있습니다. 경우보고에 봐 Lists더 당신이 원하는 무엇인가.

참조 : Java List Tutorial


구조와 같은 동적 크기의 배열을 위해 ArrayList를 사용하고 싶을 것입니다.


JAVA의 컬렉션 프레임 워크를 사용하여 배열에 요소를 동적으로 추가 할 수 있습니다. 컬렉션 프레임 워크는 기본 데이터 유형에서 작동하지 않습니다.

이 컬렉션 프레임 워크는 "java.util. *"패키지에서 사용할 수 있습니다.

예를 들어 ArrayList를 사용하는 경우

객체를 생성 한 다음 요소 수를 추가합니다 (String, Integer 등 모든 유형).

ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");

이제 3 개의 요소가 배열에 추가되었습니다.

추가 된 요소를 제거하려면

a.remove("suman");

요소를 추가하려면 다시

a.add("Gurram");

따라서 배열 크기는 동적으로 증가 / 감소합니다.


ArrayList를 사용하거나 배열로 저글링하여 배열 크기를 자동으로 증가시킵니다.


기본 배열에서 현재 위치를 계산합니다.

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

이것은 Java에서 배열에 추가하는 간단한 방법입니다. 두 번째 배열을 사용하여 원래 배열을 저장 한 다음 요소를 하나 더 추가했습니다. 그 후 나는 그 배열을 원래 배열로 다시 전달했습니다.

    int [] test = {12,22,33};
    int [] test2= new int[test.length+1];
    int m=5;int mz=0;
    for ( int test3: test)        
    {          
    test2[mz]=test3; mz++;        
    } 
    test2[mz++]=m;
    test=test2;

    for ( int test3: test)

    {
      System.out.println(test3);
    }

Java에서 배열의 크기는 고정이지만 인덱스 및 for 루프를 사용하여 고정 크기 배열에 동적으로 요소를 추가 할 수 있습니다. 아래에서 예를 찾으십시오.

package simplejava;

import java.util.Arrays;

/**
 *
 * @author sashant
 */
public class SimpleJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        try{
            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            
            }

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}

참고 URL : https://stackoverflow.com/questions/5061721/how-can-i-dynamically-add-items-to-a-java-array

반응형