Alex
Alex

Reputation: 690

Generic ArrayList of Integers Storing Strings Instead?

So here's what I am trying to do. I have a generic class called

public class SortsTextFile<T extends Comparable<T>>

That stores an ArrayList called

private ArrayList<T> listFromFile = null;

So, when it's time to grab the elements from the given text file, this code runs

try (BufferedReader in = new BufferedReader(
                                 new FileReader(listInfo)))
    {
        listFromFile = new ArrayList<>();

        String line = in.readLine();
        while (line != null)
        {
            String[] columns = line.split(FIELD_SEP);

            for (int i = 0; i < columns.length; i++)
            {
                listFromFile.add((T) columns[i]);
            }
            line = in.readLine();
        }
    }

This code runs fine, but as the title implies, instead of properly being casted into type T which would be type Integer in this case, they stay as type Strings from the text file and get added into the array as strings instead of integers.

How do I fix this? Thanks!

Upvotes: 1

Views: 724

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

T is only required to be Comparable, and String is Comparable. Also, you are adding columns which is a String[]. If you want Integer, you must convert it yourself. Assuming the values are actually integral, simplest fix would be to change

listFromFile.add((T) columns[i]);

to

listFromFile.add((T) Integer.valueOf(columns[i]));

And I'm not certain the cast is necessary. Also, I think

public class SortsTextFile<T extends Comparable<T>>

should be

public class SortsTextFile<T extends Comparable<? super T>> 

Upvotes: 3

Related Questions