programing

목록에서 정수의 적절한 삭제

prostudy 2022. 5. 27. 21:19
반응형

목록에서 정수의 적절한 삭제

여기 내가 방금 마주친 멋진 함정이 있다.정수 리스트를 생각해 봅시다.

List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(6);
list.add(7);
list.add(1);

" " " " " " " " " " " " " " " " " " 를했을 때 일이 일어날지 list.remove(1)? 그럼?list.remove(new Integer(1))이것은 몇 가지 심각한 버그를 일으킬 수 있습니다.

정수 목록을 다룰 때 특정 인덱스에서 요소를 제거하는 와 참조에 의해 요소를 제거하는 를 구분하는 적절한 방법은 무엇입니까?


여기서 고려해야 할 주요 포인트는 @Nikita가 말한 것입니다.정확한 파라미터 매칭이 자동 박스보다 우선합니다.

Java는 항상 사용자의 인수에 가장 적합한 메서드를 호출합니다.자동 복싱 및 암묵적 업캐스팅은 캐스팅/자동 복싱 없이 호출할 수 있는 방법이 없는 경우에만 수행됩니다.

List 인터페이스는 다음 두 가지 제거 방법을 지정합니다(인수 이름 지정에 유의하십시오.

  • remove(Object o)
  • remove(int index)

, ②,list.remove(1)과 '1'에서합니다.remove(new Integer(1))지정된 요소의 첫 번째 항목을 이 목록에서 삭제합니다.

캐스팅을 사용할 수 있습니다.

list.remove((int) n);

그리고.

list.remove((Integer) n);

n이 int인지 Integer인지는 중요하지 않습니다.메서드는 항상 예기하는 것을 호출합니다.

「」를 사용합니다.(Integer) n ★★★★★★★★★★★★★★★★★」Integer.valueOf(n)입니다.new Integer(n)첫 번째 두 개는 Integer 캐시를 사용할 수 있지만 이후 두 개는 항상 개체를 만듭니다.

'적절한' 방법에 대해서는 잘 모르겠지만, 당신이 제안한 방법은 잘 작동합니다.

list.remove(int_parameter);

지정된 위치에서 요소를 제거하고

list.remove(Integer_parameter);

는 지정된 개체를 목록에서 삭제합니다.

VM은 처음에 정확히 동일한 매개 변수 유형으로 선언된 메서드를 찾은 다음 자동 상자를 시도하기 때문입니다.

list.remove(4)와 완전히 일치합니다.list.remove(int index)" " " 를 list.remove(Object)을 수행합니다.list.remove((Integer)4).

list.remove(1)를 실행하면 어떤 일이 일어날지 추측할 수 있습니까?list.remove(새로운 Integer(1))는 어떻습니까?

추측할 필요가 없다. 번째 는 ""가 .List.remove(int)1이 삭제됩니다.는 ""가 .List.remove(Integer) 및 이 ""와 "Integer(1)이 삭제됩니다.두 경우 모두 Java 컴파일러는 가장 가까운 일치 과부하를 선택합니다.

네, 여기에서는 혼란(및 버그)이 발생할 가능성이 있지만, 이것은 매우 드문 사용 사례입니다.

둘 다List.remove방법은 Java 1.2에서 정의되었으며 오버로드가 모호하지 않았습니다.이 문제는 Java 1.5에 제네릭스와 자동 박스가 도입되었을 때만 발생했습니다.나중에 생각해 보니 제거 방법 중 하나에 다른 이름이 붙여졌으면 좋았을 것입니다.하지만 지금은 너무 늦었다.

VM이 올바르게 동작하지 않았더라도 다음과 같은 사실을 사용하여 적절한 동작을 보장할 수 있습니다.remove(java.lang.Object)는 임의의 오브젝트에 대해 동작합니다.

myList.remove(new Object() {
  @Override
  public boolean equals(Object other) {
    int k = ((Integer) other).intValue();
    return k == 1;
  }
}

단순히 #decitrig의 제안대로 첫 번째 답변 코멘트에서 팔로잉을 했습니다.

list.remove(Integer.valueOf(intereger_parameter));

이게 도움이 됐어요.다시 한 번 #decitrig 코멘트에 감사드립니다.누군가에겐 도움이 될 거야

자, 여기 비결이 있습니다.

여기에서는, 다음의 2개의 예를 나타냅니다.

public class ArrayListExample {

public static void main(String[] args) {
    Collection<Integer> collection = new ArrayList<>();
    List<Integer> arrayList = new ArrayList<>();

    collection.add(1);
    collection.add(2);
    collection.add(3);
    collection.add(null);
    collection.add(4);
    collection.add(null);
    System.out.println("Collection" + collection);

    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(null);
    arrayList.add(4);
    arrayList.add(null);
    System.out.println("ArrayList" + arrayList);

    collection.remove(3);
    arrayList.remove(3);
    System.out.println("");
    System.out.println("After Removal of '3' :");
    System.out.println("Collection" + collection);
    System.out.println("ArrayList" + arrayList);

    collection.remove(null);
    arrayList.remove(null);
    System.out.println("");
    System.out.println("After Removal of 'null': ");
    System.out.println("Collection" + collection);
    System.out.println("ArrayList" + arrayList);

  }

}

이제 출력을 살펴보겠습니다.

Collection[1, 2, 3, null, 4, null]
ArrayList[1, 2, 3, null, 4, null]

After Removal of '3' :
Collection[1, 2, null, 4, null]
ArrayList[1, 2, 3, 4, null]

After Removal of 'null': 
Collection[1, 2, 4, null]
ArrayList[1, 2, 3, 4]

이제 출력을 분석하겠습니다.

  1. 컬렉션에서 3이 삭제되면 콜은remove()가 취득하는 수집 방법Object o파라미터로 지정합니다.따라서 오브젝트를 삭제합니다.3그러나 arrayList 오브젝트에서는 인덱스3에 의해 덮어쓰기되므로 4번째 요소는 삭제됩니다.

  2. 두 번째 출력에서는 동일한 논리로 객체 제거 null이 두 경우 모두 제거됩니다.

그래서 번호를 삭제하려면3이 오브젝트는 3을 명시적으로 전달해야 합니다.object.

그리고 그것은 래퍼 클래스를 사용하여 주조 또는 래핑을 통해 할 수 있습니다.Integer.

예:

Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);

언급URL : https://stackoverflow.com/questions/4534146/properly-removing-an-integer-from-a-listinteger

반응형