Skip to content

Instantly share code, notes, and snippets.

@HaskellZhangSong
Created August 29, 2025 02:00
Show Gist options
  • Select an option

  • Save HaskellZhangSong/a90fded901f9f9a215e4d0692b1e0c69 to your computer and use it in GitHub Desktop.

Select an option

Save HaskellZhangSong/a90fded901f9f9a215e4d0692b1e0c69 to your computer and use it in GitHub Desktop.
import kotlin.random.Random
data class Person(val name: String, val age: Int)
/**
* A comprehensive test program that demonstrates all ArrayList APIs in Kotlin
*/
fun main() {
readln();
testConstructors()
testBasicOperations()
testCollectionOperations()
testListSpecificOperations()
testIteratorOperations()
testBulkOperations()
testUtilityOperations()
println("All ArrayList API tests completed successfully!")
}
/**
* Tests different ways to create ArrayLists
*/
fun testConstructors() {
println("\n=== Testing Constructors ===")
// Default constructor
val emptyList = ArrayList<String>()
println("Empty ArrayList: $emptyList")
// Constructor with initial capacity
val capacityList = ArrayList<Int>(10)
println("ArrayList with initial capacity 10: $capacityList (size: ${capacityList.size})")
// Constructor from collection
val fromCollection = ArrayList(listOf("apple", "banana", "cherry"))
println("ArrayList from collection: $fromCollection")
// Using arrayListOf() function
val withArrayListOf = arrayListOf(1, 2, 3, 4, 5)
println("ArrayList with arrayListOf(): $withArrayListOf")
}
/**
* Tests basic operations like add, remove, get, set
*/
fun testBasicOperations() {
println("\n=== Testing Basic Operations ===")
val list = ArrayList<String>()
// add(element)
list.add("first")
list.add("second")
println("After adding elements: $list")
// add(index, element)
list.add(1, "inserted")
println("After adding element at index 1: $list")
// get(index)
println("Element at index 0: ${list[0]}")
println("Element at index 1: ${list.get(1)}")
// set(index, element)
list[0] = "updated first"
println("After using [] to update at index 0: $list")
list.set(1, "updated inserted")
println("After using set() at index 1: $list")
// size property
println("List size: ${list.size}")
// remove(element)
val removed = list.remove("updated inserted")
println("Removed 'updated inserted': $removed, list is now: $list")
// removeAt(index)
val removedElement = list.removeAt(0)
println("Removed element at index 0 ($removedElement): $list")
// clear()
list.clear()
println("After clear(): $list")
}
/**
* Tests Collection interface operations
*/
fun testCollectionOperations() {
println("\n=== Testing Collection Operations ===")
val list = arrayListOf("apple", "banana", "cherry")
// isEmpty/isNotEmpty
println("Is list empty? ${list.isEmpty()}")
println("Is list not empty? ${list.isNotEmpty()}")
// contains
println("Contains 'banana'? ${list.contains("banana")}")
println("Contains 'grape'? ${list.contains("grape")}")
println("'cherry' in list? ${"cherry" in list}")
// containsAll
println("Contains [apple, banana]? ${list.containsAll(listOf("apple", "banana"))}")
println("Contains [apple, grape]? ${list.containsAll(listOf("apple", "grape"))}")
// indices
println("List indices: ${list.indices}")
// forEach
print("forEach loop: ")
list.forEach { print("$it ") }
println()
}
/**
* Tests List-specific operations
*/
fun testListSpecificOperations() {
println("\n=== Testing List-Specific Operations ===")
val list = arrayListOf("apple", "banana", "cherry", "apple", "date")
// indexOf
println("indexOf 'cherry': ${list.indexOf("cherry")}")
println("indexOf 'grape' (not in list): ${list.indexOf("grape")}")
// lastIndexOf
println("lastIndexOf 'apple': ${list.lastIndexOf("apple")}")
// subList
val subList = list.subList(1, 4)
println("subList from index 1 to 4: $subList")
// first/last
println("First element: ${list.first()}")
println("Last element: ${list.last()}")
// firstOrNull/lastOrNull with predicate
println("First element starting with 'c': ${list.firstOrNull { it.startsWith("c") }}")
println("Last element starting with 'z': ${list.lastOrNull { it.startsWith("z") }}")
}
/**
* Tests iterator operations
*/
fun testIteratorOperations() {
println("\n=== Testing Iterator Operations ===")
val list = arrayListOf("apple", "banana", "cherry")
// iterator
println("Using iterator:")
val iterator = list.iterator()
while (iterator.hasNext()) {
println(" ${iterator.next()}")
}
// listIterator()
println("Using listIterator:")
val listIterator = list.listIterator()
while (listIterator.hasNext()) {
val index = listIterator.nextIndex()
val element = listIterator.next()
println(" Index: $index, Element: $element")
}
// listIterator(index)
println("Using listIterator from index 1:")
val indexedIterator = list.listIterator(1)
while (indexedIterator.hasNext()) {
println(" ${indexedIterator.next()}")
}
// Modifying with ListIterator
println("Modifying with ListIterator:")
val modifyingIterator = list.listIterator()
if (modifyingIterator.hasNext()) {
modifyingIterator.next() // Move to first element
modifyingIterator.set("avocado") // Replace it
modifyingIterator.add("blueberry") // Add after it
}
println("List after modification: $list")
}
/**
* Tests bulk operations
*/
fun testBulkOperations() {
println("\n=== Testing Bulk Operations ===")
val list = arrayListOf(1, 2, 3)
// addAll(collection)
list.addAll(listOf(4, 5, 6))
println("After addAll(collection): $list")
// addAll(index, collection)
list.addAll(2, listOf(2, 3))
println("After addAll(2, collection): $list")
// removeAll
list.removeAll(setOf(2, 5))
println("After removeAll([2, 5]): $list")
// retainAll
list.retainAll(setOf(1, 3, 6))
println("After retainAll([1, 3, 6]): $list")
}
fun testUtilityOperations() {
println("\n=== Testing Utility Operations ===")
val list = arrayListOf(3, 1, 4, 1, 5, 9, 2)
// toString method test
println("\n--- Testing toString() ---")
println("toString() result: ${list.toString()}")
// Compare toString output with different collection types
val sameElementsList = listOf(3, 1, 4, 1, 5, 9, 2)
val sameElementsSet = setOf(3, 1, 4, 1, 5, 9, 2)
println("ArrayList toString: ${list.toString()}")
println("List toString: ${sameElementsList.toString()}")
println("Set toString: ${sameElementsSet.toString()}")
// toString with different element types
val mixedList = arrayListOf("string", 42, true, 3.14, Person("Alice", 30))
println("Mixed types toString: ${mixedList.toString()}")
// Empty list toString
val emptyList = arrayListOf<String>()
println("Empty ArrayList toString: ${emptyList.toString()}")
// sort
list.sort()
println("After sort(): $list")
// sortWith
val people = arrayListOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
)
people.sortWith(compareBy { it.age })
println("After sortWith by age: $people")
// sortBy
people.sortBy { it.name }
println("After sortBy name: $people")
// reverse
list.reverse()
println("After reverse(): $list")
// shuffle
list.shuffle(Random(42))
println("After shuffle(): $list")
// distinct and distinctBy
val duplicates = arrayListOf(1, 2, 2, 3, 4, 4, 4, 5)
println("List with duplicates: $duplicates")
println("Distinct elements: ${duplicates.distinct()}")
val personDuplicates = arrayListOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35),
Person("Alice", 31)
)
println("Distinct by name: ${personDuplicates.distinctBy { it.name }}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment