dimanche 3 avril 2016

HashMap entries have entire package name as value instead of desired value [duplicate]

This question already has an answer here:

I'm writing a simple java code to create a random Map and write it to a file.

This is my code:

package hit.memoryunits;
import java.util.Random;
import java.io.*;
import static java.lang.System.*;
import java.util.LinkedHashMap;
import java.util.Map;

public class HardDisk 
{
    private static HardDisk instance = null;
    private Map<Long,Page<byte[]>> pages = null;
    static final java.lang.String DEFAULT_FILE_NAME = null;
    static final int _SIZE = 50;

    private HardDisk()
    {
        pages = new LinkedHashMap<Long,Page<byte[]>>(_SIZE);
        Random rand = new Random();
        for(int i = 0; i < _SIZE; i++)
        {
            byte[] randBytes = new byte[rand.nextInt(10)];
            rand.nextBytes(randBytes);
            pages.put(Long.valueOf(i),new Page<byte[]>(Long.valueOf(i),randBytes));
        }
        try {
            writeHd();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static HardDisk getInstance()
    {
        if(instance == null)
        {
            instance = new HardDisk();
        }
        return instance;
    }

    private void writeHd() throws java.io.FileNotFoundException, java.io.IOException
    {
        out.println(pages.toString());
        try
        {
            File file = new File("HardDisk.txt");
            FileWriter fw = new FileWriter(file);
            PrintWriter pw = new PrintWriter (fw);
            for(int i = 0; i < pages.size(); i++)
            {
                pw.println(i+": " + pages.get(Long.valueOf(i)));
            }
            pw.close();
            out.print("success");
        }
        catch(IOException e)
        {
            out.println("Error");
        }
    }
}

And this is the result when I open the file:

enter image description here

I don't understand why this is happening. Whenever I print randBytes I indeed get random values, but they don't have the hit.memoryunits prefix (it's the package name). But whenever I print what pages.get returns, I get that annoying prefix.

Could someone share some light on the matter?




Aucun commentaire:

Enregistrer un commentaire