简体   繁体   中英

Java ArrayList contains method

@Override
        public boolean contains(Object object) {
            if (object != null) {
                for (E element : a) {
                    if (object.equals(element)) {
                        return true;
                    }
                }
            } else {
                for (E element : a) {
                    if (element == null) {
                        return true;
                    }
                }
            }
            return false;
        }

I am learning java and I am looking into the source code to find out how certain methods are being written. I would like to ask why is there a need to write

else {
        for (E element : a) {
            if (element == null) {
                return true;
            }
         }
    }

Thank you

Yes there is.

If object is null , object.equals(element) will throw a NullPointerException

So the case where object is null is handled in a separate loop.

Input argument can be null or not null . If it's null then we need to iterate through all list elements and return true if there is null in the array. And we have to use == operator, because equals will throw NullPointerException .

In this case your contains() method implemented to check if object value is null or not, if it is null return true otherwise false . Implementing this method give you a opportunity to check any object (passing object as a parameter) value(using if condition or any other condition). Later on when you want to check values is there or not if it is have value you can do manipulation on object.

In ArrayList contains() :

The ArrayList.contains(Object) method returns true if this list contains the specified element.

ArrayList<Integer> listObj = new ArrayList<Integer>();
listObj.add(1);
listObj.add(2);

System.out.println("Contains : "+listObj.contains(1));

This method more important check element and do somework if it is true . As a example,

if(listObj.contains(2)){
  int index=arrlist.indexOf(2);
  listObj.remove(index);
}

What is happening here is that the value(object) pass as the parameter is not a null value,

public boolean contains(Object object) {
    if (object != null) {

then go through the ArrayList element,

for (E element : a) {

is equal to pass value,

if (object.equals(element)) {

return true

Otherwise(if object is null ) go with the else block.

Throws :

ClassCastException - if the type of the specified element is incompatible with this list.

NullPointerException - if the specified element is null and this list does not permit null elements.

read more


Let's say object is a String :

This contains() method also in String class. Little bit different scenario but concept is same.

when you wish to check if one String contains a specific substring.

String word= "Hey there how are you";
if(word.contains("you")){
    System.out.println("I am fine!");
}

I would like to ask why is there a need to write

 else { 

[...]

Because otherwise, the method would always return false in the event that the condition of the if statement ( object != null ) is not satisfied, but that is inconsistent with the method's contract / documentation. Many Java List implementation can contain the value null as an element, and when they do, contains(null) must return true for them.

That is handled in a separate branch because when object is null , any attempt to invoke a method on it, such as equals() will cause a NullPointerException to be thrown. The approach in the if block therefore cannot be applied in that case.

List is a collection that allows insertion of null referenced objects into it.

the algorithm meant to tell you that if you have at least null in the list and you ask/search a null object later then it will return true at the 1st match....

because .equals() comparison method cannot be invoked on null and if you would invoke then null.equals(SOMETHING); will throw a NullPointerException . So here old traditional way comes to the rescue! use == comparison operator.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object o) method says: "returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e))." This specification should not be construed to imply that invoking Collection.contains with a non-null argument o will cause o.equals(e) to be invoked for any element e. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two elements. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

Refer: https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

有必要编写else { ...因为只有当arg'object'不为null时,if条件才成立。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM