0

I am trying to convert Linked List to Array in Java as shown in the code below

import java.io.*;
import java.util.*;

public class LinkedLst
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream fis = new FileInputStream("input");
        LinkedList<Integer> ll = new <Integer>LinkedList();
        int c;
        while((c = fis.read())!=-1)
            ll.add(new Integer(c));
        Integer[] arr = ll.toArray(new Integer[ll.size()]);
        System.out.println(arr);
        fis.close();
    }
}

with input file as follows

12
13
14
15
16

I am able to compile but I end up with the following error while running

[Ljava.lang.Integer;@2098746b

Could anybody help me with this code ?

Ashok
  • 93
  • 1
  • 1
  • 9
  • The error is due to Integer[] arr = ll.toArray(new Integer[ll.size()]); line of code – Ashok Oct 10 '14 at 10:17
  • is it an error or does the code work and give that output? you cannot print an array like that. instead, iterate through its indexes and print them separately. – İsmet Alkan Oct 10 '14 at 10:18
  • I searched other threads but their explanations did not rectify my error – Ashok Oct 10 '14 at 11:08

1 Answers1

0

That's not an error, that how the designers of Java thought you might like arrays to be printed :P

You need to print Arrays.toString(arr) to get something sane. Or you could just leave it as a list.

BTW, You are not reading 4-byte int values, you are actually reading unsigned bytes (0-255)

If you want to read a file as an array of bytes, a simpler alternative is to do.

FileInputStream fis = new FileInputStream("input");
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();

This will use a small fraction of the memory a LinkedList<Integer> will use (about 1/40th) and be much faster.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130