IT이야기

Java Array 처음에 요소를 추가하는 방법 목록

cyworld 2022. 7. 12. 21:49
반응형

Java Array 처음에 요소를 추가하는 방법 목록

에 요소를 추가해야 합니다.ArrayListqueue는 상관없습니다만, 요소를 추가하는 함수를 호출할 때 요소를 배열의 선두에 추가하고(그래서 인덱스가 가장 낮습니다), 배열에 10개의 요소가 있으면 가장 오래된 요소(인덱스가 가장 높은 요소)가 삭제됩니다.

제안해 주실 분 있나요?

List에는 메서드가 있기 때문에 다음 기능을 사용할 수 있습니다.

list.add(0, yourObject);

그런 다음 다음 마지막 요소를 삭제할 수 있습니다.

if(list.size() > 10)
    list.remove(list.size() - 1);

그러나 요구 사항을 재고하거나 다음과 같은 다른 데이터 구조를 사용하는 것이 좋습니다.

편집

Apache의 예를 들어보겠습니다.

CircularFifoQueue는 full일 경우 가장 오래된 요소를 대체하는 고정 크기의 선입선출 큐입니다.

최대 크기로 초기화하기만 하면 됩니다.

CircularFifoQueue queue = new CircularFifoQueue(10);

특정 데이터 구조 사용

첫 번째 인덱스에 요소를 추가하기 위해 최적화된 다양한 데이터 구조가 있습니다.단, 컬렉션을 이들 중 하나로 변환하는 경우 대화에는 시간과 공간의 복잡성이 필요할 수 있습니다.O(n)

데쿠

JDK에는 다음과 같은 방법을 제공하는 구조가 포함되어 있습니다.

Deque<String> deque = new LinkedList<>();
deque.add("two");
deque.add("one");
deque.addFirst("three");
//prints "three", "two", "one"

분석.

삽입의 공간 및 시간 복잡성은LinkedList일정 (O(1)Big-O치트 시트를 참조해 주세요.

목록 반전

매우 간단하지만 비효율적인 방법은 다음과 같습니다.

 Collections.reverse(list);
 list.add(elementForTop);
 Collections.reverse(list);

Java 8 스트림을 사용하는 경우 이 답변에 관심이 있을 수 있습니다.

분석.

  • 시간의 복잡성:O(n)
  • 공간의 복잡성:O(1)

JDK 구현을 보면O(n)매우 작은 목록에만 적합한 시간 복잡성입니다.

add(int 인덱스, E 요소)를 확인할 수 있습니다.

이 목록의 지정된 위치에 지정된 요소를 삽입합니다.현재 해당 위치에 있는 요소(있는 경우)와 후속 요소를 오른쪽으로 이동합니다(색인에 추가).

추가한 후 Array List의 크기를 확인하고 마지막에 있는 Array List를 삭제할 수 있습니다.

데크를 보는 게 좋을 거야목록의 첫 번째 항목과 마지막 항목에 모두 직접 액세스할 수 있습니다.

설명하신 것은 사용하기에 적절한 상황입니다.

하고 싶으니까add 및 " " " 입니다.remove하고 맨할 수 있습니다.마지막에 추가하고 처음부터 제거할 수 있습니다.그것은 큰 차이가 없을 것이다.

에는 메서드가 있습니다.add(e) ★★★★★★★★★★★★★★★★★」remove()이 명령어는 끝에 새 요소를 추가하고 이전 요소를 처음부터 제거합니다.

Queue<Integer> queue = new LinkedList<Integer>();
queue.add(5);
queue.add(6);
queue.remove();  // Remove 5

즉, 각 요소에 요소를 추가할 수 있습니다.queue 해서 뒷받침을 할 수 있어요.remove메서드 콜


업데이트: -

의 사이즈를 수정하는 경우는, 다음의 항목을 참조해 주세요.

에서 : -

CircularFifoBuffer는 First In First Out 버퍼로 크기가 고정되어 있으며 Full일 경우 가장 오래된 요소를 대체합니다.

Buffer queue = new CircularFifoBuffer(2); // Max size

queue.add(5);
queue.add(6);
queue.add(7);  // Automatically removes the first element `5`

보시다시피 최대 크기에 도달하면 새 요소를 추가하면 첫 번째 삽입된 요소가 자동으로 제거됩니다.

구현은 쉬워야 한다고 생각합니다만, 효율성을 고려하여 Array List가 아닌 Linked List를 컨테이너로 사용해야 합니다.다음의 코드를 참조할 수 있습니다.

import java.util.LinkedList;
import java.util.List;

public class DataContainer {

    private List<Integer> list;

    int length = 10;
    public void addDataToArrayList(int data){
        list.add(0, data);
        if(list.size()>10){
            list.remove(length);
        }
    }

    public static void main(String[] args) {
        DataContainer comp = new DataContainer();
        comp.list = new LinkedList<Integer>();

        int cycleCount = 100000000;

        for(int i = 0; i < cycleCount; i ++){
            comp.addDataToArrayList(i);
        }
    }
}

Java LinkedList는 목록 맨 앞에 요소를 추가하는 addFirst(E e) 메서드와 푸시(E e) 메서드를 모두 제공합니다.

https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addFirst(E)

리스트 메서드를 사용하여 삭제 및 추가할 수 있습니다.

list.add(lowestIndex, element);
list.remove(highestIndex, element);

이 코드를 사용할 수 있습니다.

private List myList = new ArrayList();
private void addItemToList(Object obj){
    if(myList.size()<10){
      myList.add(0,obj);
    }else{
      myList.add(0,obj);
      myList.remove(10);
    }
}

사용할 수 있습니다.

public List<E> addToListStart(List<E> list, E obj){
list.add(0,obj);
return (List<E>)list;

}

데이터 유형으로 E 변경

가장 오래된 요소를 삭제해야 할 경우 다음을 추가할 수 있습니다.

list.remove(list.size()-1); 

반환 전.그렇지 않으면 목록에 개체가 처음 추가되고 가장 오래된 요소도 유지됩니다.

목록의 마지막 요소가 삭제됩니다.

import java.util.*:
public class Logic {
  List<String> list = new ArrayList<String>();
  public static void main(String...args) {
  Scanner input = new Scanner(System.in);
    Logic obj = new Logic();
      for (int i=0;i<=20;i++) {
        String string = input.nextLine();
        obj.myLogic(string);
        obj.printList();
      }
 }
 public void myLogic(String strObj) {
   if (this.list.size()>=10) {
      this.list.remove(this.list.size()-1);
   } else {
     list.add(strObj); 
   }
 }
 public void printList() {
 System.out.print(this.list);
 }
}
import com.google.common.collect.Lists;

import java.util.List;

/**
 * @author Ciccotta Andrea on 06/11/2020.
 */
public class CollectionUtils {

    /**
     * It models the prepend O(1), used against the common append/add O(n)
     * @param head first element of the list
     * @param body rest of the elements of the list
     * @return new list (with different memory-reference) made by [head, ...body]
     */
    public static <E> List<Object> prepend(final E head, List<E> final body){
        return Lists.asList(head, body.toArray());
    }

    /**
     * it models the typed version of prepend(E head, List<E> body)
     * @param type the array into which the elements of this list are to be stored
     */
    public static <E> List<E> prepend(final E head, List<E> body, final E[] type){
        return Lists.asList(head, body.toArray(type));
    }
}

기존 어레이의 선두에 요소를 추가하고 기존 요소를 오른쪽으로 이동시켜 가장 오래된 요소(array[length-1])를 폐기하려고 할 때도 비슷한 문제가 있었습니다.내 솔루션은 그다지 성능이 좋지 않을 수 있지만 내 목적에 맞게 작동합니다.

 Method:

   updateArray (Element to insert)

     - for all the elements of the Array
       - start from the end and replace with the one on the left; 
     - Array [0] <- Element

행운을 빌어요

다음 예를 들어보겠습니다.

List<String> element1 = new ArrayList<>();
element1.add("two");
element1.add("three");
List<String> element2 = new ArrayList<>();
element2.add("one");
element2.addAll(element1);

언급URL : https://stackoverflow.com/questions/12949690/java-arraylist-how-to-add-elements-at-the-beginning

반응형