Arrays are one of the most common data structures in Java- and in programming as a whole-as are Strings. Strings are sometimes treated as primitives in other languages-even though they are just fundamentally dynamic char arrays.
What you may have noticed is a weird discrepancy that pertains to Java having .length for arrays, and .length() for String objects.
This boils down to a side effect of Java’s limited object-oriented programming, but one that also is not necessarily an issue for other languages, as will be discussed later.
Yes, Strings are objects, but they actually inherit from the interface CharSequence. One property of an interface in Java is that it cannot contain fields. It only has the capability of defining abstract method definitions.
As a result, .length() has to be a method. The method .length() may be treated differently in the varying other inheriters of the class as well, so this makes sense. But did I know this even though I knew Java for 4 years? Nope. Fundamentally, you are almost never going to even use those different implementations in the first place. So in essence, this makes Oracle’s life easier- not yours. Sorry.
For arrays, the field length is made public, as well as final. The keyword public makes it accessible upon construction of the object (kind of a given there), but final on a side-note creates an important distinction. Final is a keyword that indicates an immutable (or unchanging state) once the object is initialized. This makes sense, as once you initialize an array with a size or an array literal of elements, it will remain at a fixed size. As there is no interface inheritance here, interface, nor a reason to define length differently with arrays, it is a field with arrays- not a method.
public class ExampleDataStructure {
public final int length;
public ExampleDataStructure(int l) {
length = l;
}
//Throws Error, will not compile
public void SetLength(int l) {
length = l;
}
}
A basic demonstration of why final is used in order to give arrays their fixed size upon initialization.
Like Java, C# has 3 main means of specifying inheritance; abstract classes, concrete class inheritance, and interface inheritance.
While C# is still restricted to the restriction that interfaces are exclusively behavioral specification (no stored variables), C# does allow for properties to be defined within interfaces. This is utilized within the interface implementations of data structures, for example:
public sealed class ExampleDataStructure : ICollection {
public int Count
{
get => innerCol.Count;
}
public bool IsReadOnly
{
get => false;
}
}