list2 내부에있는 목록 기반에서 요소 개체 목록을 제거하고 싶습니다. 나는 removeAll ()을 사용했다. 목록이 list2에있는 요소를 제거하지 않는 이유는 무엇입니까?
Element.java
public class Element {
private String element;
public Element() {
}
public Element(String element) {
setE(element);
}
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
}
RemoveAllTest.java
import java.util.ArrayList;
import java.util.List;
public class RemoveAllTest {
public RemoveAllTest() {
List<Element> list = new ArrayList<Element>();
List<Element> list2 = new ArrayList<Element>();
list.add(new Element("a"));
list.add(new Element("b"));
list.add(new Element("c"));
list2.add(new Element("a"));
list2.add(new Element("b"));
list.removeAll(list2);
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getElement());
}
}
public static void main(String[] args) {
new RemoveAllTest();
}
}
Element 클래스는 equals를 구현하지 않습니다. 왜냐하면 그들은 정확히 동일한 객체인지 테스트하는 Object.equals () 메서드를 사용하기 때문입니다. (즉 ==입니다).
equals를 구현하는 경우 동일한 객체가 Map과 같은 해시 데이터 구조의 동일한 버킷으로 해시되도록 hashCode도 구현하는 것이 좋습니다.
이 문제가없는 요소는 다음과 같습니다.
public class Element {
private String element;
public Element() {
}
public Element(String element) {
setE(element);
}
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
public boolean equals(Object other) {
if (other instanceof Element) {
Element otherElement = (Element) other;
if (null == element) {
return otherElement.element == null;
}
return element.equals(otherElement.element);
}
return false;
}
public int hashCode() {
if (null == element) {
return -7;
}
return element.hashCode();
}
}
요소에 정상적인 값이 있는지 확인하지 않기 때문에 요소가 null 인 경우주의해야합니다. "더 나은"요소 클래스는 적절한 경우 String을 취하는 생성자를 제공하고 생성자에 전달 된 문자열이 null 인 경우 또는 setElement 호출이 null 값을 취하는 경우 IllegalArgumentException을 발생시킴으로써이를 피할 수 있습니다. 이렇게 :
public class Element {
private String element;
public Element(String element) {
setElement(element);
}
public String getElement() {
return element;
}
public void setElement(String element) {
if (null == element) {
throw new IllegalArgumentException("Element must not be null.");
}
this.element = element;
}
public boolean equals(Object other) {
if (other instanceof Element) {
Element otherElement = (Element) other;
return element.equals(otherElement.element);
}
return false;
}
public int hashCode() {
return element.hashCode();
}
}
마지막으로, 등호를 쉽게 잊고 요소에 null을 할당 할 수 있으므로 null == 요소가 element == null보다 작성하는 것이 좋습니다. null = 요소를 작성하면 컴파일러는 삭제 된 문자에 대해 불평하고 경고합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다