Java list comparison resulting in error I can't pin down

507 views java
-5

I'm working on this script to compare elements sequentially in a list/array in Java. Essentially the code takes in a CSV converts it to a list and iterates over the list's size. When I attempt a comparison between the values I run into an error I can't figure out in this case:

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Float (java.lang.String and java.lang.Float are in module java.base of loader 'bootstrap')
at list.main(list.java:22)

The code is:

public class list{

public static void main(String[] args){
    System.out.println("Enter your filename");
    Scanner inputValue = new Scanner(System.in);
    String fileLocation = inputValue.nextLine();
    try {
    String checkvalue = new String(Files.readAllBytes(Paths.get(fileLocation)));
    ArrayList<Float> listValues = new ArrayList(Arrays.asList(checkvalue.split("[\\r\\n]+")));
    System.out.println(listValues);
    for (int i = 0; i < listValues.size(); i++){
        System.out.println(listValues.get(i));
        float valueA = listValues.get(i);
        float valueB = listValues.get(i+1);
        if (valueA <= valueB){
            System.out.println("True");
        }
    }
    }
    catch (IOException e){
        e.printStackTrace();
    }
}

}

answered question

String split returns a string. so listValues is actually an ArrayList<String> but you've declared it an ArrayList<Float>.

Ah, ok, that makes sense. I'm coming from Python if that clarifies the mistake, type conversions are very straightforward compares to here. In this case, I guess I generate the list, then convert the list elements into floats afterward? Or is there a doc where I can read up on how to convert directly to a float by this method?

new ArrayList instantiates a raw type. You should have a warning on that line. You want new ArrayList<Float> or just new ArrayList<>.

@DanielPryden: Technically true but there's an issue with conversion between the type of lists which would be better explained in an answer.

@Makoto: Yes, I just saw that as well.

1 Answer

8

 ArrayList<Float> listValues = new ArrayList(Arrays.asList(checkvalue.split("[\\r\\n]+")));

checkvalue.split(...) returns a string. So the right hand side of this expression builds up an ArrayList<String>. You've declared listValues as ArrayList<Float>, though, so it's trying to tell you that you have a type mismatch.

To solve, you'll need to parse the String into a float. Java's Float class has a nice parseFloat method you can use:

ArrayList<Float> listValues = new ArrayList(Arrays.asList(Float.parseFloat(checkvalue.split("[\\r\\n]+"))));

posted this

Have an answer?

JD

Please login first before posting an answer.