简体   繁体   中英

Why are a list of short objects not able to check if it contains the value or not

I'm just starting to learn collections. When I try to check if the value 5 that was previously added is present or not, It always returns me false.

List<Short> shortList = new ArrayList<>();
shortList.add((short) 5);
System.out.println(shortList.contains(5));

Output : false

I don't understand what's so wrong about this? This is such a common logic.

I faced the same issue a couple of years ago. This is what I found back then.

Short Answer : The value 5 gets converted to Integer Object due to Auto-Boxing. When ArrayList checks for the value, it compares each object with .equals() operator and the .equals of Integer, Short will go ahead with comparing their primitive values (.intValue or .shortValue) only if both the objects are of the same Type.

Long Answer :

When Performing shortList.contains(5) The following happens :

  1. Auto-Boxing kicks in, resulting in 5 Getting converted to Integer Object.

     Integer.valueOf(int) line: 830 
  2. The ArrayList's Contains method internally calls indexOf API which checks at what Index is the object being searched is present.

:

 public int indexOf(Object o) {
    ...
        // Here Object "o" is of Type Integer in your case, So It calls Integer.equals
        if (o.equals(elementData[i]))
    ...
    // If not equal or not found.
    return -1;
    }
  1. Since the object passed is of Type Integer Wrapper Class, it invokes Integer Class equals() Method.
  2. The Implementation of Integer Class equals is

:

 public boolean equals(Object obj) {
            if (obj instanceof Integer) {
                return value == ((Integer)obj).intValue();
            }
            return false;
        }

Since the Object "obj" here is of type "Short", the instanceof operator fails resulting in false as the output.

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