-3

I wanted to convert the Arraylist <String> to array double and i used the following code:

String [] n = (String[]) lines.toArray();

String[] array = lines.toArray(new String[lines.size()]);

double[] nums = new double[n.length];
for (int i= 0 ; i< nums.length; i++){
      nums[i] = Double.parseDouble(n[i]);

but then i have the following error:

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader 'bootstrap')

could anybody help me?

9
  • 2
    How is lines defined? Commented Jan 21, 2020 at 18:45
  • 2
    What is the purpose of String [] n = (String[]) lines.toArray(); (which seems to be cause of the exception and strangely you provided code with solution to that error in next line String[] array = lines.toArray(new String[lines.size()]);)? Commented Jan 21, 2020 at 18:48
  • 1
    Since the error message explicitly states cast exception, a good starting point would be the first line of the code and see if the cast to String[] makes sense. Commented Jan 21, 2020 at 18:49
  • according to the stacktrace, lines is an Object[] and you simply cast it to String[]. Commented Jan 21, 2020 at 18:54
  • 1
    @Mohsen The declaration of your List please if we can see it we can help Commented Jan 21, 2020 at 19:05

2 Answers 2

1

Don't have to create String array and convert it to double array. Can directly convert arraylist of String into Array of double. could try something like below..

import java.util.Arrays;
import java.util.List;

public class Snippet {

    public static void main(String... s) {
        List<String> lines = Arrays.asList("10.12", "22.56"); // you might not need this line
        double[] nums = new double[lines.size()];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Double.parseDouble(lines.get(i));
            System.out.println(nums[i]);//added just to print data in array
        }
    }

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

Comments

1

I'm not really sure what to make of the code you've posted - but to answer your question:

ArrayList<String> arrayListOfStrings = new ArrayList<String>();
arrayListOfStrings.add("1.1");
arrayListOfStrings.add("3.6");
Double[] arrayOfDoubles = new Double[arrayOfDoubles.size()];
for(int i=0;i<arrayListOfStrings.size();i++){
    arrayOfDoubles[i] = Double.parseDouble(arrayListOfStrings.get(i));
}
System.out.print("" + arrayOfDoubles[0]);
System.out.print("" + arrayOfDoubles[1]);

Very similar to question posted here: From Arraylist to Array

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.