Sum of ArrayList for different types

Is it possible to write a single method total to do a sum of all elements of an ArrayList, where it is of type <Integer> or <Long>?

I cannot just write

public long total(ArrayList<Integer> list)

and

public long total(ArrayList<Long> list)

together as there will be an error of erasure, and Integer does not automatically extends to Long and vice versa... but the code inside is identical!

--------------Solutions-------------

Yes, you can implement such a method, since both Integer and Long extend Number. For example you can use a wildcard type for the list element type:

public static long total(List<? extends Number> list) {
long sum = 0;
for (Number n : list) {
sum += n.longValue();
}
return sum;
}

This only works for the integral types however, since the sum variable and the return value are of type long.

Ideally you would like to be able to also use the method with Floats and Doubles and return an object of the same type as the list element type, but this is not easy to do for two reasons:

  1. The only thing you can do with a Number is to get its value as one of the primitive number types. You can not sum two of them in a number dependent way.
  2. It is not possible to create a 0-object of the right class.

You can use Java´s generics for this

public <T extends Number> T total(List<T> list) {
T sum = 0;
for (T n : list) {
sum += n.longValue();
}
return sum;
}

Knowing that T will always be a Number, things are simplified. However, this solution could work also for Strings, if necessary. The only change would be in the extends part.

You can also use streams in Java 8

public static <T extends Number> long sumList(List<T> list)
{
return list.stream().mapToLong(a -> a.longValue()).sum();
}

Category:java Time:2018-11-30 Views:1
Tags: java arraylist

Related post

  • using Single class for different types of combobox 2011-08-03

    I have a combobox cbpaymenttype have values like(DD , CASH ,CARD) I have list view Named as listviewcashmembers with items lastname(xxxx), firstname(xxx), postcode(xxx), ddrerefernce(xxxx), ddprovider(xxx) Monthlyamount(xxx) MembershipType(xxxx), Sta

  • How do I import my folders, setup for different types of email and locate my old address book? 2014-03-04

    Original title: Outlook install missing info. I have Installed outlook 2010 on a new computer (windows 7)and set up according to instructions given by the service provider. I find that I did not import my settings including the different folders I ha

  • Which is the most versatile CSS framework for different types of layouts? 2009-12-11

    I would like to know which is the most versatile CSS layout applicable to most or all types of different layouts? --------------Solutions------------- No CSS Framework can possibly be applicable to all different types of layouts, you will have to cho

  • Advice on handling widgets for different types of data (MVC) 2010-04-21

    I have a few widgets I need to show on a site - they are all relating to different types of data (e.g user, house). Each type of data and its relations is represented in specific models, but as far as a controller or helper is concerned, is it an ok

  • Drupal 6: Drupal Themer gives same candidate name for different type of content types 2010-06-03

    I'm a drupal newbie... I have different type of contents like News, Events, etc. and their content is different. News detail page has title-content text-date. but Events detail page has title-date-content text-location-speaker-etc. So I need differen

  • Edit controls for different types 2010-11-23

    I need to let the user edit different types of objects. Are there any existing libraries that have edit-controls for types ranging from float, bool, int, string, filename, color etc. ? (preferably with features like validation, range-checking etc.) I

  • Java: Using one Method for different types in the array parameter 2011-02-09

    I just cant't figure this out maybe you can help me. The problem: public class class1 implements Comparable<class1> { public int compareTo(class1 o) { //some code } } public class class2 implements Comparable<class2> { public int compareT

  • Lucene.NET Boost for different type of entity 2011-03-01

    I am new to Lucene.NET and have already run into a (I think) difficult problem. I have an object lets say a "Company", now there are 3 different types of companies ordered by importance from low to high. If I query for a search term I would like to g

  • Resolving urls to different views for different types of user profiles in Django 2011-07-09

    I'm adding a new type of user profile to site and this new type of user(say new_type) should not be able to reach the same views like the existings users. My question is: how can i use different types of views according to user type using the same re

  • what does the mySQL Length parameter do for different types? 2009-10-21

    I've used MySQL (via PHPMyAdmin) a lot before but never really understood half of it. I'm assuming that for varchar, length is the maximum length of a string that can go there. But what about for Int? According to this, Int is a 4 byte integer, so wh

  • Ideal HTTP cache control headers for different types of resources 2010-06-04

    I want to find a minimal set of headers, that work with "all" caches and browsers (also when using HTTPS!) On my web site, I'll have three kinds of resources: (1) Forever cacheable (public / equal for all users) Example: 0A470E87CC58EE133616F402B5DDF

  • Are static members of a generic class different for different types in Java? 2010-08-10

    @Spence asked this Previous Question. So, how's that work in Java? Generic types are discarded at runtime in Java, so what happens to static variables of classes instantiated with different generic types? --------------Solutions------------- Static m

  • CakePHP Making Child Models for different types of Comments 2012-02-29

    I have a Comment Model that I am using to store comments for both Goals and Notes. The current implementation has a GoalComment Model and a NoteComment Model, each of which extends Comment, and the Comment's beforeFind does the following: $queryData[

  • How to sort 2 ArrayLists of different types of data in the same order? 2012-01-03

    Suppose I have an ArrayList of String and an ArrayList of int. My ArrayList of Strings contains: index : value ----------------- 0 : "Paul" 1 : "Peter" 2 : "Maria" My ArrayList of Integers contians: index : value ----------------- 0 : 2 1 : 0 2 : 1 S

  • Is having different users for different types of queries a good practice? 2008-09-29

    I am using MySQL and PHP for a project I am working. I have created separate users for carrying out different functions (one for running select queries, one for running update queries, etc.) to provide an extra layer of security. This way, I figure i

  • How to display a different JSP view for different types of objects 2009-07-14

    Assuming I have a list of Animal(s) with standard polymorphic behavior like Cat(s) and Dog(s). What is the best approach to display a different JSP view for each one in the list? <c:forEach var='animal' items='${animals}'> //show a different te

  • Custom thumbnails for different types of multimedia 2011-02-18

    I am looking to create thumbnails for a number of different document types (mp4, pdf, png, and ppt). I have seen different methods for doing them individually - MPMovieplayerController: requestThumbnailImagesAtTimes or get UIGraphicsGetCurrentContext

  • convert an arraylist of different types 2011-03-21

    I have an arraylist that could contain 1 of 3 types (switch1, switch2, switch3). How do I convert this to a List? var switches = _switch.Switches; var newList = switches.Cast<SwitchObj>().ToList(); This didn't work. Here is what is in each of s

  • A single table to keep reports for different type of information 2011-12-05

    I have many kind of information like 'messages', 'comments', 'articles', 'reviews', ... stored in different tables in my DB. I would like to make a 'report' functionnality for each one of them but I don't want overload the DB and limit the amount of

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 2.779 (s). 15 q(s)