CodeGym /Java Blog /무작위의 /자바 배열 목록
John Squirrels
레벨 41
San Francisco

자바 배열 목록

무작위의 그룹에 게시되었습니다
안녕! 이전 레슨에서는 배열에 대해 자세히 살펴보고 배열 작업의 일반적인 예를 검토했습니다. 이 레슨에서는 Java ArrayList에 대해 자세히 살펴보겠습니다. 일반적으로 배열은 매우 편리합니다. 그리고 이미 알아차리셨듯이 배열로 많은 일을 할 수 있습니다 :) 그러나 배열에는 여러 가지 단점이 있습니다.
  • 제한된 크기. 배열을 생성할 때 배열에 포함해야 하는 요소 수를 알아야 합니다. 과소 평가하면 공간이 충분하지 않습니다. 과대 평가하면 어레이가 반쯤 비어 있는 상태로 유지되며 이는 좋지 않습니다. 결국, 여전히 필요한 것보다 더 많은 메모리를 할당하고 있습니다.

  • 배열에는 요소를 추가하는 메서드가 없습니다. 요소를 추가하려는 위치의 인덱스를 항상 명시적으로 지정해야 합니다. 필요한 값이 차지하는 위치에 대한 인덱스를 실수로 지정하면 덮어씁니다.

  • 항목을 삭제하는 방법은 없습니다. 값은 "제로화"만 가능합니다.

public class Cat {

   private String name;

   public Cat(String name) {
       this.name = name;
   }

   public static void main(String[] args) {

       Cat[] cats = new Cat[3];
       cats[0] = new Cat("Thomas");
       cats[1] = new Cat("Behemoth");
       cats[2] = new Cat("Lionel Messi");

       cats[1] = null;

      
      
       System.out.println(Arrays.toString(cats));
   }

   @Override
   public String toString() {
       return "Cat{" +
               "name='" + name + '\'' +
               '}';
   }
}
출력: [Cat{name='Thomas'}, null, Cat{name='Lionel Messi'}] 다행히 Java 작성자는 배열의 장단점을 잘 알고 있으므로 Java ArrayList 라는 매우 흥미로운 데이터 구조를 만들었습니다 . 가능한 한 간단하게 말하면 Java ArrayList 는 많은 새로운 기능이 포함된 "완성된" 배열입니다.

ArrayList를 만드는 방법

매우 쉽게 생성할 수 있습니다.

ArrayList<Cat> cats = new ArrayList<Cat>();
이제 Cat 개체를 저장하기 위한 목록을 만들었습니다 . 자동으로 확장될 수 있기 때문에 ArrayList 의 크기를 지정하지 않는다는 점에 유의하십시오 . 이것이 어떻게 가능한지? 사실 아주 간단합니다. 놀랍겠지만 Java의 ArrayList는 매우 일반적인 배열 위에 구축됩니다. :) 예, 여기에는 배열이 포함되어 있으며 여기에 요소가 저장됩니다. 그러나 Java의 ArrayList 에는 해당 배열을 사용하는 특별한 방법이 있습니다.
  • 내부 배열이 채워지면 ArrayList는 내부적으로 새 배열을 만듭니다. 새 배열의 크기는 이전 배열의 크기에 1.5를 더한 값입니다.

  • 모든 데이터가 이전 어레이에서 새 어레이로 복사됩니다.

  • 이전 어레이는 가비지 수집기에 의해 정리됩니다.
이 메커니즘을 통해 Java ArrayList (일반 배열과 다름)는 새 요소를 추가하는 메서드를 구현할 수 있습니다. add()방법 입니다

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<Cat>();
   cats.add(new Cat("Behemoth"));
}
새 항목이 목록 끝에 추가됩니다. 이제 어레이 오버플로 위험이 없으므로 이 방법은 완전히 안전합니다. 그건 그렇고, ArrayList는 인덱스로 객체를 찾을 수 있을 뿐만 아니라 그 반대도 마찬가지입니다. 참조를 사용하여 ArrayList에서 객체의 인덱스를 찾을 수 있습니다 ! 이것이 indexOf() 메서드의 용도입니다. 원하는 객체에 대한 참조를 전달하고 indexOf()는 해당 인덱스를 반환합니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   int thomasIndex = cats.indexOf(thomas);
   System.out.println(thomasIndex);
}
출력: 0 맞습니다. 우리의 thomas 개체는 실제로 요소 0에 저장됩니다. 배열에는 단점만 있는 것이 아닙니다. 그들은 또한 의심의 여지가 없는 이점을 가지고 있습니다. 그중 하나는 인덱스로 요소를 검색하는 기능입니다. 인덱스, 즉 특정 메모리 주소를 가리키기 때문에 이러한 방식으로 배열을 검색하는 것은 매우 빠릅니다. ArrayList할 줄도 안다! get () 메서드는 다음을 구현합니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   Cat secondCat = cats.get(1);

   System.out.println(secondCat);
}
출력: Cat{name='Behemoth'} 또한 ArrayList 에 특정 개체가 포함되어 있는지 쉽게 확인할 수 있습니다. 이는 ArrayList contains() 메서드를 사용하여 수행됩니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   cats.remove(fluffy);
   System.out.println(cats.contains(fluffy));
}
메서드는 ArrayList 의 내부 배열에 요소가 포함되어 있는지 확인하고 부울 (true 또는 false)을 반환합니다. 출력: false 그리고 삽입에 대한 또 다른 중요한 사항입니다. ArrayList를 사용하면 인덱스를 사용하여 배열의 끝뿐만 아니라 어디에나 요소를 삽입할 수 있습니다. 이를 위한 두 가지 방법이 있습니다.
  • ArrayList 추가(int 인덱스, Cat 요소)
  • ArrayList 집합(int 인덱스, Cat 요소)
인수로 이 두 메서드 모두 삽입하려는 위치의 인덱스와 개체 자체에 대한 참조를 사용합니다. 차이점은 set()을 사용하여 삽입하면 이전 값을 덮어쓴다는 것입니다. add()를 사용하여 삽입하면 먼저 [인덱스]에서 배열의 끝까지 모든 요소를 ​​하나씩 이동한 다음 결과 빈 위치에 지정된 객체를 추가합니다.

예를 들면 다음과 같습니다.


public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);

   System.out.println(cats.toString());

   cats.set(0, lionel);// Now we have a list of 2 cats. Adding a 3rd using set

   System.out.println(cats.toString());
}
출력: [[Cat{name='Thomas'}, Cat{name='Behemoth'}] [Cat{name='Lionel Messi'}, Cat{name='Behemoth'}] 고양이 2마리의 목록이 있었습니다 . 그런 다음 set() 메서드를 사용하여 요소 0으로 다른 것을 삽입했습니다 . 결과적으로 이전 요소가 새 요소로 대체되었습니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);

   System.out.println(cats.toString());

   cats.add(0, lionel);// Now we have a list of 2 cats. Adding a 3rd using add

   System.out.println(cats.toString());
}
여기서 add()가 다르게 작동하는 것을 볼 수 있습니다. 모든 요소를 ​​오른쪽으로 이동한 다음 새 값을 요소 0으로 씁니다. 출력: [Cat{name='Thomas'}, Cat{name='Behemoth'}] [Cat{name='Lionel Messi'}, Cat{name='Thomas'}, Cat{name='Behemoth'}] 목록을 완전히 지우려면 clear() 메서드를 사용합니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   cats.clear();

   System.out.println(cats.toString());
}
출력: [] 목록에서 모든 항목이 제거되었습니다. 참고: 배열과 달리 ArrayList는 toString() 메서드를 재정의 하고 이미 목록을 문자열로 적절하게 표시합니다. 일반 배열에서는 이를 위해 Arrays 클래스를 사용해야 했습니다 . 그리고 배열에 대해 언급한 이후로 Java를 사용하면 배열과 ArrayList 사이를 쉽게 "전환"할 수 있습니다 . 즉, 하나를 다른 것으로 변환할 수 있습니다. Arrays 클래스 에는 이를 위한 Arrays.asList() 메서드가 있습니다 . 내용을 배열로 가져와 ArrayList 생성자에 전달하는 데 사용합니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();


   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   Cat[] catsArray = {thomas, behemoth, lionel, fluffy};

   ArrayList<Cat> catsList = new ArrayList<>(Arrays.asList(catsArray));
   System.out.println(catsList);
}
출력: [Cat{name='Thomas'}, Cat{name='Behemoth'}, Cat{name='Lionel Messi'}, Cat{name='Fluffy'}] 반대 방향으로도 갈 수 있습니다 . ArrayList 객체 의 배열 . toArray() 메서드를 사용하여 이 작업을 수행합니다 .

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();

   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   Cat[] catsArray = cats.toArray(new Cat[0]);

   System.out.println(Arrays.toString(catsArray));
}
참고: toArray() 메서드 에 빈 배열을 전달했습니다 . 이것은 오류가 아닙니다. ArrayList 클래스 내에서 이 메서드는 빈 배열을 전달하면 성능이 향상되는 방식으로 구현됩니다. 미래를 위해 이것을 염두에 두십시오(물론 특정 크기의 배열을 전달할 수 있습니다. 그것도 작동합니다). 아, 크기에 대해. 목록의 현재 크기는 size() 메서드를 사용하여 찾을 수 있습니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();


   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   System.out.println(cats.size());
}
배열의 길이 속성 과 달리 ArrayList.size() 메서드는 원래 용량이 아니라 실제 요소 수를 반환한다는 점을 이해하는 것이 중요합니다 . 결국 ArrayList 를 만들 때 크기를 지정하지 않았습니다 . 그러나 지정할 수 있습니다. ArrayList 에는 적절한 생성자가 있습니다. 그러나 새 요소를 추가하는 측면에서 이것은 동작을 변경하지 않습니다.

public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>(2);// create an ArrayList with an initial capacity of 2


   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Behemoth");
   Cat lionel = new Cat("Lionel Messi");
   Cat fluffy = new Cat ("Fluffy");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(lionel);
   cats.add(fluffy);

   System.out.println(cats.size());
}
콘솔 출력: 4 2개의 요소 목록을 만들었지만 필요할 때 조용히 확장되었습니다. 또 다른 고려 사항은 처음에 매우 작은 목록을 만들면 더 자주 확장해야 하므로 일부 리소스가 사용된다는 것입니다. 이 레슨에서 ArrayList 에서 요소를 제거하는 프로세스에 대해서는 거의 다루지 않았습니다 . 나중에 보게 될 별도의 강의에 이 주제를 넣었습니다 :) 학습 한 내용을 보강하려면 Java 과정에서 동영상 강의를 시청하는 것이 좋습니다.
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION