3

I have a array which I convert to string to use it as key in an hashmap. How is it possible to convert a string like this [5.0, -1.0, 2.0] again to an array consisting of three double values?

PS: I'm kind of new to java but I couldnt find a solution here or via google.

Karl Adler
  • 15,780
  • 10
  • 70
  • 88
  • http://stackoverflow.com/a/3272808/86515 combined with Double.parseDouble – KitsuneYMG Apr 29 '13 at 19:44
  • http://stackoverflow.com/questions/9101301/how-to-convert-string-array-to-double-array-in-one-line http://stackoverflow.com/questions/2454137/java-converting-string-in-array-to-double Try these. – j.jerrod.taylor Apr 29 '13 at 19:46
  • 2
    Why not use a `List` as the key in the hash map, rather than a `String`? Trying to dump it into a `String` is definitely a code smell. – Louis Wasserman Apr 29 '13 at 19:46
  • +1 for Louis' comment, but remember not to modify the list after you've started using it as a hash key. better yet, use an immutable list (like you'll find in the guava library) – Sean Patrick Floyd Apr 29 '13 at 19:51

5 Answers5

0

There isn't any ready method for this. So, you have to create your own method, which will parse your string back into array of double-s. You can do it, using String.split(...) method for example.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
0

See documentation for String.substring() and String.split().

akostadinov
  • 17,364
  • 6
  • 77
  • 85
0
Scanner sc = new Scanner(stringToParse);
ArrayList<Double> buffer = new ArrayList<>();
while(sc.hasNextDouble())
    buffer.add(sc.nextDouble());
Object[] doubles = buffer.toArray();
gparyani
  • 1,958
  • 3
  • 26
  • 39
0

Something like this might work

List<Double> yourDoubleList = new ArrayList<Double>();
String withoutBrackets = array.substring(1, array.length() - 1);
for(String number : withoutBrackets.split(",")) {
    yourDoubleList.add(Double.parseDouble(number));
}
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
0

It's possible, with a bit of fiddling - and by the way, it's a very, very bad idea to use an array as a key to a Map (even if it's converted to a String), because it can change its contents. Try this:

String array = "[5.0, -1.0, 2.0]";
String[] data = array.substring(1, array.length()-1).split(", ");
double[] answer = new double[data.length];
for (int i = 0; i < data.length; i++)
    answer[i] = Double.parseDouble(data[i]);

Now answer will be an array of doubles with the values originally contained in the String.

Óscar López
  • 232,561
  • 37
  • 312
  • 386