Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Array.Sort() and Array.IndexOf() methods static?

Always was interested why are Array.Sort() and Array.IndexOf() methods made static and similar ArrayList.Sort() and ArrayList.IndexOf() are designed as member methods. Thank you for any ideas.

like image 439
Alexander Prokofyev Avatar asked Oct 07 '08 04:10

Alexander Prokofyev


People also ask

Is IndexOf static method?

indexOf() is a static method of the StringUtils used to find the index of the first occurrence of the search sequence in the given text.

Can you use IndexOf for an array?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.

How do you find the index of an element in an array?

JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.


2 Answers

In my view Array class is basically a class representation of the fixed size arrays that we declare using [] in program (you can draw the analogy like int has it's class (structure) representation as System.Int32).

Also Array class does not contain the actually array data in any instance variables but it provides just static utility functions which can be utilized to do sorting and searching in the declared fixed size arrays.

On the other hand, ArrayList is a collection class, which provides dynamic size array implementation and it has it's own data-structure to contain the data. Therefore the said methods are instance methods, so that they can work on the that particular instance's data.

like image 175
jatanp Avatar answered Sep 19 '22 23:09

jatanp


A collection class like ArrayList encapsules some kind of internal storage (presumably an array which is resized as needed, but it could also be a linked list or some other implementation). Metods like IndexOf and Sort needs access to the underlying private storage to be efficient, so they have to be instace methods.

An Array on the other hand is not encapsulated, there is public access directly to the storage. The Array.IndexOf and Array.Sort methods does not need any special access to the array data, so they might as well be static metods.

like image 35
JacquesB Avatar answered Sep 17 '22 23:09

JacquesB