0

My code:

private Collection<Film> getFilms() {
    File files = new File(pathname);
    File[] filesList = files.listFiles();
    List<Film> list = Arrays.asList();
    Log.d("filesList.length ", ""+filesList.length);
    for (int i = 0; i < filesList.length; i++) {
        try {
            Film filmTemp = new Film(filesList[i]);
            list.set(i, filmTemp);
        } catch (Throwable e) {
            Log.d("Error!", "Kobzda", e);
        }
    }
    return list;
}

And I always get the same errors:

  • java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
  • java.lang.ArrayIndexOutOfBoundsException: length=0; index=1
  • Might be relevant -- I feel using `Arrays.asList()` is part of the issue? https://stackoverflow.com/questions/16748030/difference-between-arrays-aslistarray-and-new-arraylistintegerarrays-aslist – aug Jan 25 '19 at 22:17
  • You might want to refer to https://stackoverflow.com/a/5554781/6818446 – S. Czop Jan 25 '19 at 22:20

2 Answers2

0

You are calling Arrays.asList() with no params which means the list you are creating is immutable (cannot add or remove elements) and empty.

Even if the List was mutable (say, by doing List<Film> list = new ArrayList<>()) you'd still run into an issue because you can't call set on a non-existent element index. In other words, an element has to already exist at that index in the List in order to successfully call set.

Instead, you should create a mutable List and call add.

Something like:

private Collection<Film> getFilms() {
    File files = new File(pathname);
    File[] filesList = files.listFiles();
    List<Film> list = new ArrayList<>();
    Log.d("filesList.length ", ""+filesList.length);
    for (int i = 0; i < filesList.length; i++) {
        try {
            Film filmTemp = new Film(filesList[i]);
            list.add(filmTemp);
        } catch (Throwable e) {
            Log.d("Error!", "Kobzda", e);
        }
    }
    return list;
}
Michael Krause
  • 4,689
  • 1
  • 21
  • 25
0

If you take a look at the docs for List#set

Replaces the element at the specified position in this list with the specified element.

Throws: ...

IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

(Emphasis added.)

So this method doesn't add a new element at the given index, it replaces an element that must already be there. But when you instantiated the list using Arrays.asList(), you created an empty list. Since there's no element at index 0, you can't replace one there.

You should create the list using new ArrayList<>(), and then use List#add (Arrays.asList() returns a List that can't add elements to new indices; its size is fixed).

yshavit
  • 42,327
  • 7
  • 87
  • 124