Object interaction in Java - Time & Space Complexity
When objects talk to each other in a program, it takes time. We want to see how this time grows when we have more objects or more interactions.
How does the number of object interactions affect the program's speed?
Analyze the time complexity of the following code snippet.
class Person {
void greet(Person other) {
System.out.println("Hello, " + other.getName());
}
String getName() {
return "Friend";
}
}
class Demo {
static void greetAll(Person[] people) {
for (Person p : people) {
p.greet(p);
}
}
}
This code makes each person greet themselves by calling a method on each object in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of Person objects and calling greet on each.
- How many times: Once for each person in the array (n times).
As the number of people grows, the number of greetings grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings |
| 100 | 100 greetings |
| 1000 | 1000 greetings |
Pattern observation: The work grows directly with the number of people.
Time Complexity: O(n)
This means if you double the number of people, the time to greet doubles too.
[X] Wrong: "Calling a method on an object inside a loop makes the time complexity more than linear."
[OK] Correct: Each method call here is simple and happens once per object, so it adds a fixed amount of work per item, keeping the growth linear.
Understanding how objects interact and how that affects time helps you explain your code clearly and think about efficiency in real projects.
"What if greet called another method that loops over all people? How would the time complexity change?"