Junior — Middle
Kuidas hinnata ArrayListis elemendi otsimise tõhusust väärtuse järgi?
sobes.tech AI
Vastus AI-lt
In an ArrayList, searching for an element by value is usually implemented using the contains() or indexOf() methods, which traverse the elements from start to end, comparing each with the sought value. The efficiency of such a search is O(n), where n is the number of elements in the list, because ArrayList does not index elements by value.
Example:
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
boolean found = list.contains("banana"); // traversing elements
If a faster search by value is needed, it is better to use hash-based data structures such as HashSet or HashMap.