0

これはかなり標準的な問題のように思えますが、単純すぎてどうすればよいかわかりません。SO の他の場所で読んだことから、これは、パラメーターを指定せずに ArrayLists が初期化されたときに Generics が原因です。をコメントアウトしても警告が表示されないことも知っているArrayList<Integer> p = (ArrayList<Integer>)is.readObject();ので、 を にキャストしようとすると、コンパイラにジェネリックの安全性の問題があると確信してObjectArrayList<Integer>ます。ArrayListこれを引き起こさずに保存するにはどうすればよいですか?

コードは次のとおりです。

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

public class FileTest
{
    public static void main(String[] args)
    {
        String fileName = "fred.txt";
        ArrayList<Integer> a = new ArrayList<Integer>();
        a.add(2);
        a.add(3);
        a.add(4);
        try
        {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
            os.writeObject(a);
            os.close();
        }
        catch(FileNotFoundException e){e.printStackTrace();}
        catch(IOException e){e.printStackTrace();}
        try
        {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileName));
            ArrayList<Integer> p = (ArrayList<Integer>)is.readObject();
            //for(int i : p) System.out.println(i);
        }
        catch(FileNotFoundException e){e.printStackTrace();}
        catch(IOException e){e.printStackTrace();}
        catch(ClassNotFoundException e){e.printStackTrace();}
    }
}
4

1 に答える 1

2

オブジェクトをArrayListにキャストしようとすると、コンパイラにジェネリックの安全性の問題があると確信しています。

ジェネリックの安全性の問題だけでなく、の安全性の問題です。次のものは でありArrayList、それを安全に使用できると想定していますArrayList<Integer>.

これを引き起こさずに ArrayList を保存するにはどうすればよいですか?

あなたの問題はそれを保存することではなく、それを取り戻すことです。@SuppressWarnings("unchecked")宣言の前に何かを追加します。

于 2013-10-19T09:37:30.407 に答える