2017-09-23 204 views
0

我從文件中讀取矩陣,並且所有列都有不同的數據類型。 我無法找到一個結構來保存和操作我的數據。感謝幫助。java中的數據類型和動態綁定

// 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; 
     } 
    } 
+0

當然我的代碼不工作;-) –

回答

0

我從你的任務的理解,你想在一個單一的集合中的所有單值,而不是陣列(糾正我,如果我錯了)。你基本上可以把他們(幾乎)你喜歡(我用的ArrayList)任何集合,你有問題是基本數組需要裝箱之前,你可以將它們添加到您的收藏:

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 
} 
+0

謝謝,我可以解決我的問題。 –

+0

非常好。那麼你能接受答案來結束這個問題嗎? – JensS