0

There are 2 overridden methods in ArrayList:

public boolean add(E e)

public void add(int index, E element)

What are the general rules, according to which add(longArg) cannot box it and call add(E e), giving me compile error (thus actually prohibiting me from overloded call to add(E e):

    ArrayList<Long> lst = new ArrayList<>();            
    lst.add(2); // c.ERR, see below
         // method add(int, Long) in the type ArrayList<Long> 
        // is not applicable for the arguments (int)   

P.S. Eclipse (SE7) compiler.

Code Complete
  • 3,146
  • 1
  • 15
  • 38

2 Answers2

0

Because you are trying to add an integer. If you instruct the compiler to consider it to be a long add a L or l to the number

 ArrayList<Long> lst = new ArrayList<>();            
 lst.add(2L); // now it can be autoboxed

Executed in Java 9's JShell:

jshell>  ArrayList<Long> lst = new ArrayList<>();            
lst ==> []

jshell> lst.add(2);
|  Error:
|  no suitable method found for add(int)
|      method java.util.Collection.add(java.lang.Long) is not applicable
|        (argument mismatch; int cannot be converted to java.lang.Long)
|      method java.util.List.add(java.lang.Long) is not applicable
|        (argument mismatch; int cannot be converted to java.lang.Long)
|      method java.util.AbstractCollection.add(java.lang.Long) is not applicable
|        (argument mismatch; int cannot be converted to java.lang.Long)
|      method java.util.AbstractList.add(java.lang.Long) is not applicable
|        (argument mismatch; int cannot be converted to java.lang.Long)
|      method java.util.ArrayList.add(java.lang.Long) is not applicable
|        (argument mismatch; int cannot be converted to java.lang.Long)
|  lst.add(2);
|  ^-----^

jshell> lst.add(2l);
$2 ==> true
M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
0

When you use generics you will have to include a reference to a type of object that is going in the List. In this case you are trying to tell the ArrayList to reference only values of type long, or int or double, etc...

You need to declare the objects that will be referenced in a generic by using big D Double and Big I Integer and Big L Long as these are object types.

I'm not too sure if you can box a Long as an object type but check your API and you will see. 

Hope this code works:

ArrayList<Long> lst = new ArrayList<Long>();
Himanshu Ray
  • 38
  • 1
  • 12