2
@Parameters
public static Collection data() throws IOException {       
   ArrayList<String> lines = new ArrayList();

   URL url = PokerhandTestCase.class.getClassLoader().getResource("test/TestFile.txt");
   File testFile = new File(url.getFile());
   FileReader fileReader = new FileReader(testFile);
   bufReader = new BufferedReader(fileReader);
   assertFalse("Failed to load the test file.", testFile == null);

   boolean isEOF = false;
   while (!isEOF){

        String aline = bufReader.readLine();

        if (aline == null){
            System.out.println("Done processing.");
            isEOF = true;
        }

        lines.add(aline);   
   }

   return Arrays.asList(lines); 

 }

プログラムの最後の行がクラッシュを引き起こしています。arrayList からコレクションを定義する適切な方法を教えてください。この関数は、戻り値の型として Collection に必要です。

4

3 に答える 3

3

最後の行を次のように置き換えます。

return (Collection)lines;

ArrayList は Collection インターフェイスを実装しているため: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

したがって、全体的なコード:

  public static Collection data() throws IOException 
  {
    ArrayList<String> lines = new ArrayList();
    // populate lines collection...
    return (Collection)lines;
  }

以下のコメントに基づいて、おそらくこれは「配列のコレクション」と見なされます。

  public static Collection data() throws IOException 
  {
    ArrayList<String> array1 = new ArrayList();
    ArrayList<String> array2 = new ArrayList();
    ArrayList<String> array3 = new ArrayList();
    // populate lines collection...
    ArrayList<ArrayList<String>> lines = new ArrayList();
    lines.add(array1);
    lines.add(array2);
    lines.add(array3);
    return (Collection)lines;
  }
于 2013-03-22T03:30:04.843 に答える
0

返すコレクションはCollection<Object[]>. コレクションを返しています。次のようなことをする必要があります (完全な例):

@RunWith(Parameterized.class)
public class MyTest {
    @Parameters
    public static Collection<Object[]> data() throws IOException {
        List<Object[]> lines = new ArrayList<>();

        File testFile = new File("/temp/TestFile.txt");
        FileReader fileReader = new FileReader(testFile);
        BufferedReader bufReader = new BufferedReader(fileReader);
        Assert.assertFalse("Failed to load the test file.", testFile == null);

        boolean isEOF = false;
        while (!isEOF) {
            String aline = bufReader.readLine();

            if (aline == null) {
                System.out.println("Done processing.");
                isEOF = true;
            }

            lines.add(new Object[] { aline });
        }

        return lines;
    }

    private final String file;

    public MyTest(String file) {
        this.file = file;
    }

    @Test
    public void test() {
        System.out.println("file=" + file);
    }

}

ここでファイルを閉じていないことに注意してください。リストの最後に無駄な null 値を追加していますが、コードをコピーしました:-)。

于 2013-03-22T06:57:36.253 に答える
0

ArrayList 行 = 新しい ArrayList(); ... return Arrays.asList(lines);

これは二次元配列を返します。

この関数は、戻り値の型として Collection に必要です。

user1697575 さんの答えは正しいと思います。

于 2013-03-22T04:02:10.667 に答える