Arrays are contiguous collections of elements accessed by index. In object-oriented programming (OOP), arrays often serve as fundamental building blocks inside classes and interfaces. You will frequently encapsulate arrays within objects, expose safe views or iterators, maintain invariants (like sorted order), and leverage polymorphism through element types.
ArrayList, C#'s List<T>) wrap dynamic arrays.std::array<T, N> (fixed) and std::vector<T> (dynamic) are preferred in OOP designs.Arrays carry an element type. How that type interacts with inheritance varies by language:
Cat[] can be treated as an Animal[], but storing a Dog into that array causes a runtime error. Convenient but potentially unsafe.List<T> (in Java/C#) or std::vector<T> (in C++) are usually invariant by default, catching more errors at compile time.ArrayList, List<T>, std::vector<T>, Python list.get(i), set(i, v) with bounds checks.for/foreach loops; expose iterators or generator methods instead of raw arrays.fill, copy, slice, sort, map/filter/reduce (language-dependent).public final class IntSeries {
private final int[] data;
public IntSeries(int[] values) {
this.data = java.util.Arrays.copyOf(values, values.length); // defensive copy
}
public int size() { return data.length; }
public int get(int i) { return data[i]; }
public int sum() {
int s = 0;
for (int v : data) s += v;
return s;
}
public int[] toArray() {
return java.util.Arrays.copyOf(data, data.length); // do not leak internal array
}
}
// Usage:
// IntSeries s = new IntSeries(new int[]{1,2,3});
// int total = s.sum();
class Grades:
def __init__(self, scores):
self._scores = list(scores) # defensive copy
def average(self):
return sum(self._scores) / len(self._scores) if self._scores else 0.0
def add(self, score):
self._scores.append(score)
def to_list(self):
return list(self._scores) # return a copy
class Buffer {
std::vector<int> data_;
public:
explicit Buffer(std::size_t n) : data_(n) {}
int& operator[](std::size_t i) { return data_[i]; }
const int& operator[](std::size_t i) const { return data_[i]; }
std::size_t size() const { return data_.size(); }
};
Arrays.equals, Arrays.hashCode).