Pergunta

My question is about the topic of casting Generic Java types. Suppose we have an Integer ArrayList like so:

List<Integer> intFileContents = new ArrayList<Integer>(8192);

Now, I want to retrieve one Integer from the list, and then print it out as a character, since the ArrayList actually reads characters from a text file:

while ((fileBuffer = stream.read())!= -1) {
    intFileContents.add(fileBuffer);
    System.out.print(fileBuffer);
}

If I was using primitive types, I'd just cast it like this:

char someChar = (char)someInt;

However, casting Generic types (Character)intFileContents.get(pos); is impossible, since they are objects. Now, there is a method in the Integer class: Integer.toString(), which should return said Integer as a string. Unfortunately, all it does is, if we f.e. had and Integer = 255, the String would be "255". That is not what I want, since casting primitive ints to chars gives a character of the correct ASCII code, so f.e. casting (char)65 would return someChar = 'A'. This is exactly what I want to get, except with Generic types. What is the way to achieve this?

Foi útil?

Solução

There are a few options here. One thing you can do is get the integer value, then cast/print that:

(char) intFileContents.get(pos).intValue(); // Do something with this

Probably a better option would be to convert the int values you read in immediately, like this:

List<Character> charFileContents = new ArrayList<Character>(8192);

while ((fileBuffer = stream.read())!= -1) {
    charFileContents.add((char) fileBuffer); // <-- Do the cast before storing the value
    System.out.print(fileBuffer);
}

Then, when you go to print the character, it is already the proper type. Be warned that this only works for one specific encoding (don't remember which), so if you want another encoding you'll have to use a InputStreamReader instead of a plain InputStream

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top