0

For an assignment, we had to write a method sum that expects a List as a parameter. The method returns an int representing the sum of the integers in the list.

Would the code turn out to be:

public int getSum (List <Integer> list) {
int sum = 0; 
for (int i = list) 
sum = sum + i; 
return sum; 
}

I'm confused on when to use Integer vs int in this scenario. Thanks in advance!

Edit: If possible, could you guys edit my code?

BJ Myers
  • 6,617
  • 6
  • 34
  • 50
Destinox
  • 11
  • 4
  • possible duplicate of [when and where to use int vs Integer](http://stackoverflow.com/questions/10623682/when-and-where-to-use-int-vs-integer) – Aman Gupta Dec 03 '14 at 05:04
  • In List or Any other collection using generic type, we have to use Class rather than primitive type, this is the reason why you have to use Integer when using List. Integer is a boxing type of int.https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html – JaskeyLam Dec 03 '14 at 05:04

4 Answers4

1

Integer is a Object/Wrapper Class int is a primitive type, Here is the link for you to understand more

Secondo
  • 451
  • 4
  • 9
1

No need to confuse. Your code seems correct to me. In java Wrapper classes are provided for premitive types. Java manages boxing/unboxing for those premitive type variable to their respective wrapper classes. e.g. Integer for int Long for long etc.
Usually Wrapper classes (Integer) turns to useful when considered for comparing object or to perform some class level operation such as equals() and hashCode() method, and also Collection framework require Object type not premitive type.

Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
0

Collections in java are generic class that you can use them to collect any object but not primary types. So you cannot use List<int>. If you are interested in using collections such as List, you have to use Integer.

public int getSum (List <Integer> list) {
    int sum = 0; 
    for (int i : list) 
        sum = sum + i; 
    return sum; 
}
Misagh Emamverdi
  • 3,654
  • 5
  • 33
  • 57
0

Java collections use autoboxing concept. So for most cases you don't need to worry about the conversion. This is internally handled (i.e. from boxed to unboxed(primitive) type).

Below is the snippet:

public int getSum (List<Integer> list) {
   int sum = 0; 
   for (int elem : list) 
    sum += elem; 
   return sum; 
}
nitishagar
  • 9,038
  • 3
  • 28
  • 40