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.

4
  • stackoverflow.com/a/3272808/86515 combined with Double.parseDouble Commented Apr 29, 2013 at 19:44
  • stackoverflow.com/questions/9101301/… stackoverflow.com/questions/2454137/… Try these. Commented Apr 29, 2013 at 19:46
  • 2
    Why not use a List<Double> as the key in the hash map, rather than a String? Trying to dump it into a String is definitely a code smell. Commented Apr 29, 2013 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) Commented Apr 29, 2013 at 19:51

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Comments

0
Scanner sc = new Scanner(stringToParse);
ArrayList<Double> buffer = new ArrayList<>();
while(sc.hasNextDouble())
    buffer.add(sc.nextDouble());
Object[] doubles = buffer.toArray();

2 Comments

the last line should be Double[] doubles = buffer.toArray(new Double[buffer.size()])
This answer returns a Double[], OP was asking for a double[]
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));
}

2 Comments

This answer returns a List<Double>, OP was asking for a double[]
@ÓscarLópez yes, but arguably the list is still a better choice for usability (at least for a small number of doubles)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.