Programing

ArrayList 삽입 및 검색 순서

lottogame 2020. 10. 18. 08:18
반응형

ArrayList 삽입 및 검색 순서


5 개의 문자열을 ArrayList. 삽입 및 검색 순서 ArrayList는 동일합니까?


아래 코드를 확인하고 실행하십시오.

public class ListExample {

    public static void main(String[] args) {
        List<String> myList = new ArrayList<String>();
        myList.add("one");
        myList.add("two");
        myList.add("three");
        myList.add("four");
        myList.add("five");

        System.out.println("Inserted in 'order': ");
        printList(myList);
        System.out.println("\n");
        System.out.println("Inserted out of 'order': ");

        // Clear the list
        myList.clear();

        myList.add("four");
        myList.add("five");
        myList.add("one");
        myList.add("two");
        myList.add("three");

        printList(myList);
    }

    private static void printList(List<String> myList) {
        for (String string : myList) {
            System.out.println(string);
        }
    }
}

다음 출력을 생성합니다.

Inserted in 'order': 
one
two
three
four
five


Inserted out of 'order': 
four
five
one
two
three

자세한 정보는 문서를 참조하십시오. List (Java Platform SE7)


. ArrayList는 순차 목록 입니다. 따라서 삽입 및 검색 순서는 동일합니다.

검색 중에 요소를 추가 하면 순서가 동일하게 유지되지 않습니다.


항상 끝에 추가하면 각 요소가 끝에 추가되고 변경할 때까지 그대로 유지됩니다.

항상 처음에 삽입하면 각 요소는 추가 한 역순으로 나타납니다.

중간에 넣으면 순서가 달라집니다.


Yes, it will always be the same. From the documentation

Appends the specified element to the end of this list. Parameters: e element to be appended to this list Returns: true (as specified by Collection.add(java.lang.Object))

ArrayList add() implementation

public boolean More ...add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

참고URL : https://stackoverflow.com/questions/11331591/arraylist-insertion-and-retrieval-order

반응형