Tool for converting variables of different types in Java

Suppose I want to perform some non-trivial (not only type conversions) conversions on a variable v, for example, from type T1 (String) to T2 (List):

String v = "123";
List<Integer> list = new ArrayList<Integer>(); 

      

One solution would be like this:

for(int i = 0; i < v.length(); i++) {
    char c = v.charAt(i);
    int intVal = Character.getNumericValue(c);
    list.add(intVal);
}

      

However, if conversions are done between different types, manual solutions for all patterns will be tedious and inefficient.

The question is, is there any automatic conversion tool of this kind?

Thank,

+3


source to share


1 answer


What you are asking for (im assuming some sort of typing tool that can work for just about anyone) doesn't exist. It would be useless for something like this to be inlined, because there are so many different ways for people to want an object to be represented in other formats.

If you want to have a tool to convert a string to an ints array, you can easily make this tool yourself, something like



ArrayList<Integer> stringToArray(String v)
{
  List<Integer> list = new ArrayList<Integer>(); 
  for(int i = 0; i < v.length(); i++) {
    char c = v.charAt(i);
    int intVal = Character.getNumericValue(c);
    list.add(intVal);
  }
  return list;
}

      

Making your own functions to go from one type of object to another is the best way to do this.

0


source







All Articles