Sunday, November 3, 2013

Store numbers of different types in a List

To store numbers of different types (Integer, Float, Double...) in a single List, we can define the list of type Number.

Example:

package javanumber;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaNumber {

    public static void main(String[] args) {
        List<Number> numberList = new ArrayList<>();
        numberList.add((int)123);
        numberList.add(123456.7);
        numberList.add((double)456.789);
        numberList.add(0.1f);
        
        for(Number num:numberList){
            System.out.println(num + " of type " + num.getClass());
        }
    }
}

List contain numbers of different type
A single List contain numbers of Integer, Double and Integer

No comments:

Post a Comment