I like to examine a Excel .csv column which may be of type String,Int oder Double. I implement a classic generic Pair class:
public class PairT<K,V> implements Comparable<PairT<K,V>>
In case of an integer column the column values are stored in:
ArrayList<PairT<Integer,Integer>> column_list = new ArrayList<>();
where the V
value holds the excel row index.
Code snippet below shows the nasty solution - I would improve:
// Add a cell value of type T to the column list
@SuppressWarnings("unchecked")
public static <T> void addCell(
String excelcell,
int row_idx,
boolean ignorecase,
T defkey,
/*IO*/ArrayList<PairT<T,Integer>> column_list) throws RuntimeException
{
//Class<?> classtype = defkey.getClass(); String typename = classtype.getSimpleName();
char type;
if (defkey instanceof String) type = 'S';
else if (defkey instanceof Integer) type = 'I';
else if (defkey instanceof Double) type = 'D';
else type = 'O'; // other
T key;
try
{
switch(type)
{
case 'I':
try
{ key = (T)new Integer(excelcell);
} catch (NumberFormatException e) { key = defkey; }
column_list.add(new PairT<T,Integer>(key,row_idx));
break;
case 'D':
try
{ key = (T)new Double(excelcell);
} catch (NumberFormatException e) { key = defkey; }
column_list.add(new PairT<T,Integer>(key,row_idx));
break;
case 'S':
if (ignorecase) excelcell = excelcell.toUpperCase();
column_list.add(new PairT<T,Integer>((T)excelcell,row_idx));
break;
default: // Other take the .toString() output as key
column_list.add(new PairT<T,Integer>((T)excelcell.toString(),row_idx));
}
}catch (Exception ex) // possibly a ClassCastException
{
throw new RuntimeException("addCell(): Problems using PairT<K,V>",ex);
}
} //----- end of addCell()
To test I use:
ArrayList<PairT<Integer,Integer>> column_list = new ArrayList<>();
int row_idx = 0;
boolean ic = true; // for String values only;
Integer defval = new Integer("0");
String cell = "12";
addCell(cell,row_idx,ic,defval,column_list);
cell = "17.34"; // leads to def val
addCell(cell,++row_idx,ic,defval,column_list);
cell = "456";
addCell(cell,++row_idx,ic,defval,column_list);
cell = "foo"; // lead to def avlue
addCell(cell,++row_idx,ic,defval,column_list);
System.out.println("result: " + column_list);
// [12;0, 0;1, 456;2, 0;3]
java.util.Collections.sort(column_list);
System.out.println("Sorted: " + column_list);
//Sorted: [0;1, 0;3, 12;0, 456;2]
It works as expected, however -as I said- I dont want to distinguish the Type T in addCell(). I would prefer a short solution, something like:
if (ignorecase) column_list.add(new PairT<T,Integer>((T)excelcell.toUpperCase(),row_idx));
else column_list.add(new PairT<T,Integer>((T)excelcell,row_idx));