Search code examples
javadata-structuresprimitivedynamic-binding

Data Type and Dynamic Binding in java


I read a matrix from a file and all column have a different data type. I can't find a structure to hold and manipulate my data. Thank's for help.

    // I read a matrix from file and all column have a different type.
    int[]    iT = new int[] {1,3,5};
    long[]   lT = new long[] {123, 456, 789};
    double[] dT = new double[] {1.2d, 3.2d, 5.2d};

    // I like to know if there are a kind of structure to hold and manipulate it.
    Collection<Object[]> collection = new HashSet<Object[]>();

    collection.add(iT);
    collection.add(dT);
    collection.add(lT);     

    for(Object[] obj : collection) {

        String type = obj.getClass().getSimpleName();

        switch (type) {

        case "double[]":
            for(Object element : obj) System.out.println(element);
            break;

        case "int[]":
            for(Object element : obj) System.out.println(element);
            break;

        case "long[]":
            for(Object element : obj) System.out.println(element);
            break;
        }
    }

Solution

  • From my understanding of your task,you want all single values in a single collection, not the arrays (correct me if I'm wrong). You can basically put them in (almost) any collection you like (I have used ArrayList), the problem you have is that the primitive arrays need to be boxed before you can add them to your collection:

    public static void main(String[] args) {
        int[] iT = new int[] { 1, 3, 5 };
        long[] lT = new long[] { 123, 456, 789 };
        double[] dT = new double[] { 1.2d, 3.2d, 5.2d };
    
        Integer[] boxedInts = IntStream.of(iT).boxed().toArray(Integer[]::new);
        Long[] boxedLongs = LongStream.of(lT).boxed().toArray(Long[]::new);
        Double[] boxedDoubles = DoubleStream.of(dT).boxed().toArray(Double[]::new);
    
        Collection<Object> collection = new ArrayList<>();
    
        collection.addAll(Arrays.asList(boxedInts));
        collection.addAll(Arrays.asList(boxedLongs));
        collection.addAll(Arrays.asList(boxedDoubles));
    
        for (Object element : collection) {
            System.out.print(element.toString() + " ");
        }
        //prints 1 3 5 123 456 789 1.2 3.2 5.2 
    }