Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使一个大的物体变得不可复制_Java_Loops_Iterator - Fatal编程技术网

Java 使一个大的物体变得不可复制

Java 使一个大的物体变得不可复制,java,loops,iterator,Java,Loops,Iterator,我有50个文件,每个100MB大小 在我的代码中,每个文件都有一个类表示,例如: public class FileRepresentation { private String path; public FileRepresentation(String path) { this.path = path; } public String getPath() { return this.path; } }

我有50个文件,每个100MB大小

在我的代码中,每个文件都有一个类表示,例如:

public class FileRepresentation
{
    private String path;

    public FileRepresentation(String path)
    {
        this.path = path;
    }

    public String getPath()
    {
        return this.path;
    }
}
public class FileRepresentation
{
    private String path;

    public FileRepresentation(String path)
    {
        this.path = path;
    }

    public String getPath()
    {
        return this.path;
    }
}
由于显而易见的原因,我不能在我的内存中有50个对象,每个100MB,而我在其中循环

我有一个类,它保存了所有文件的目录路径,我想让这个类是可编辑的,并且能够一次返回一个对象,这意味着来自迭代器(循环)的每个请求,它创建一个新对象并返回它

public class FilesClass
{
    private String folderPath;

    public FilesClass(String folderPath)
    {
        this.folderPath= folderPath;
    }

    //What I want to achieve:
    public FileRepresentation getNextFile()
    {
        return new FileRepresentation("nextFile");
    }
}
我曾经考虑过使用一个计数器,每次迭代只创建一个新对象,但这似乎是错误的。 我怎样才能做到呢?有没有更好的办法?也许我弄错了,在循环中不是所有的50个对象都在内存中

谢谢

编辑:
我最终提出了我的建议方法。

我最终使用了我的活套方法:

公共类文件类
{
私人清单文件;
专用int计数器;
公共文件类(列出文件)
{
this.files=文件;
这个计数器=0;
}
公共文件表示getNextFile()
{
FileRepresentation object=myOwnImplementationToConvertFileToObject(this.files.get(counter++));
返回对象;
}
}

为什么不编写一个包含try-with-resources块的循环来打开、使用和关闭一个文件呢?“我曾经考虑过…”并不是不实际尝试某项操作的有效理由。你可以创建一个路径集合,迭代该路径,并在循环内部对该文件执行读取和所有操作。我从来没有说过我没有尝试过它,我说我相信这是错误的,还有更好的方法@但是,这里甚至没有任何合法企图的暗示。这比任何相反的声明都更有说服力。幸运的是,你可以编辑你的问题,包括你的尝试和结果,希望在你的问题结束之前。
public class FilesClass
{

    private List<File> files;

    private int counter;

    public FilesClass(List<File> files)
    {
        this.files = files;
        this.counter = 0;
    }

    public FileRepresentation getNextFile()
    {
        FileRepresentation object = myOwnImplementationToConvertFileToObject(this.files.get(counter++));
        return object;
    }
}