Ok-Alex
Ok-Alex

Reputation: 558

Java List.set() changing list size. Why?

I'm writing android app, which drawing 4 graphs in 1 plot. Graph data is stored in object GraphViewData(x,y). I also have List which contains 4 GraphVieData objects.

I want to give user ability to switch off/on some graphs.

I tried to write myList.set(index, null) to hide graph and then myList.set(index, myObject) to show it again, but every time the List size is changing. So I'm getting IndexOutOfBound exception.

Please, tell me why the List size is changing? Here is List.set() description:

Replaces the element at the specified location in this List with the specified object. This operation does not change the size of the List.

Code:

public void removeSerie(int id){
    graphSeries.set(id, null);
    Log.d("CurrentListSize: ", graphSeries.size() + "");
}
public void addSerie(GraphViewData series, int id){
    graphSeries.set(id, series);
}

Upvotes: 1

Views: 626

Answers (1)

Stephen C
Stephen C

Reputation: 718946

There is a discrepancy between the javadocs for List.set(int, T) between Java and Android. This is worrying, but you should resolve it as following:

  • The Oracle version of the javadoc is definitive for Java. A List implementation is permitted to change the list size on set.

  • The Android version of the javadoc should be viewed as incorrect as a source for Java. You could argue that it is correct for Android, but that doesn't really help if you are dealing with code that wasn't specifically written for Android. (For example, code that was written for Java and then compiled for Android.)

  • The standard List classes in Java and Android won't do this. (Check the source code to be sure, but I'd be extremely surprised if any of them did without the javadocs saying so.)

  • A custom / 3rd-party List class could do this, and still follow the Java List contract (though arguably not the Android contract).

  • There are no guarantees that a custom / 3rd-party List class will follow either contract. This renders the whole argument moot ... unless you can persuade the relevant author / supplier to change the relevant list class. (And good luck with that, because it will probably break other peoples' code!!)


So what should you do? I recommend:

  • If you want to be able to do this with set, make sure that you are using a list class that supports it. Check the code of the list class if necessary.

  • Otherwise, change your algorithm.

Upvotes: 4

Related Questions