Java Collection Framework – ArrayList The Java Collection Framework (JCF) is a unified architecture that provides a set of interfaces, implementations and algorithms to store, manipulate and process a group of objects efficiently. In simple terms, it standardizes how collections such as lists, sets and queues are represented and accessed in Java. The core hierarchy starts from the Collection interface and is mainly divided into: List, Set and Queue. (Note: Map is part of the framework but does not extend the Collection interface.) ArrayList is a resizable array implementation of the List interface. ArrayList – Properties • Implements List interface • Uses a resizable (dynamic) array internally • Allows duplicate elements • Maintains insertion order • Allows random access using index • Allows null values • Not synchronized (not thread-safe by default) Commonly Used ArrayList Methods • add(E e) – adds an element to the list • add(int index, E e) – inserts element at a specific position • get(int index) – retrieves element at a given index • set(int index, E e) – replaces element at a given index • remove(int index) – removes element at a given index • remove(Object o) – removes a specific object • size() – returns the number of elements • isEmpty() – checks whether the list is empty • contains(Object o) – checks if an element exists • indexOf(Object o) – returns the first occurrence index • clear() – removes all elements Ways to Access (Iterate) an ArrayList • Using Iterator • Using ListIterator • Using for loop (index-based loop) • Using enhanced for-each loop Short example An ArrayList can be traversed either by moving through its indices, or by using iterator-based mechanisms depending on whether forward-only or bidirectional traversal is required. #Java #CoreJava #CollectionsFramework #ArrayList #JavaLearning #JavaDeveloper #InterviewPreparation Sharath R, Bibek Singh, Santhosh HG, Harshit T, Ravi Magadum, Vamsi yadav
Siddhardha Tummala’s Post
More Relevant Posts
-
Core Java Fundamentals :Key Traits of Metaspace Permanent Generation in Java PermGen (Permanent Generation) was a memory area in the Java Virtual Machine (JVM) used before Java 8 to store class metadata, interned strings, and static variables. It was part of the JVM heap space and had a fixed size, making it difficult to manage memory efficiently. Fixed and Hard-to-Tune Size in PermGen PermGen had a fixed maximum size, which was often too small for applications with many classes. Correct Tuning was Tricky Even though it was configurable using -XX:MaxPermSize, tuning it correctly was difficult. PermGen was not dynamically expanding Unlike Metaspace, on the other hand, dynamically expands using native memory, eliminating manual tuning issues. OutOfMemoryError If class metadata exceeded 256MB, the application would crash with OutOfMemoryError: PermGen space. Key Features of Metaspace Stores Class Metadata It holds information about classes, methods, and their runtime representations (like method bytecode and field details). Unlike PermGen, it does not store Java objects (which reside in the heap). Uses Native Memory Unlike PermGen, which had a fixed maximum size, Metaspace dynamically expands using native memory(outside the heap), reducing Out of memory errors. Automatic Growth & GC Handling The JVM automatically manages Metaspace size based on the application’s needs. Class metadata is garbage collected when classes are no longer needed (such as when an application uses dynamic class loading). Configurable Maximum Size -XX:MaxMetaspaceSize=256m // Limits Metaspace to 256MB -XX:MetaspaceSize=128m // Initial size before expanding ☕ If this helped you — support my work: 👉 Buy Me a Coffee -https://lnkd.in/ebXVUJn2 #JVMInternals #JavaPerformance #MemoryManagement #SpringBoot #Microservices #SystemDesign
To view or add a comment, sign in
-
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
Most Java devs know you can't use multiple inheritance. But do you know all the types you CAN'T extend — even without the final keyword? 🤔 The rule is simple: a class can only extend ONE parent. But Java has several types that block inheritance through different mechanisms — not always with final. Here's the full picture: → final class: The obvious one. Compiler blocks extension directly. → enum: Implicitly extends java.lang.Enum. Since Java doesn't allow multiple inheritance, no room for your class. → record (Java 16+): Implicitly final. Compiler rejects any attempt to extend it. → Arrays (int[], String[], etc.): They extend Object — confirmed by the Java Language Specification. But the JVM creates them at runtime, not as regular classes. You cannot extend them. Period. → Private constructor: No final needed. Since every child class must call super(), a private constructor silently kills inheritance. ```java class Singleton { private Singleton() { } // blocks extension AND multiple instances public static Singleton getInstance() { ... } } class Child extends Singleton { } // ❌ Won't compile ``` This is why the Singleton pattern gets a free "sealed" behavior — not by design choice, but as a side effect of the private constructor. The key insight: final is just ONE of the ways Java prevents inheritance. The language has multiple mechanisms, some explicit, some implicit, some enforced by the JVM itself. Understanding WHY something can't be extended makes you a better architect — not just a better coder. 🎯 📊 Java Language Specification - Arrays (JLS §10): https://lnkd.in/eSyKYpip 📊 Java Language Specification - Types and Values (JLS §4): https://lnkd.in/e5EGb-ps 📊 Java Arrays and Inheritance — Medium (Santiago Barbieri, 2024): https://lnkd.in/e9vziKWt #Java #SoftwareEngineering #BackendDevelopment #ObjectOrientedProgramming #CleanCode #JavaDeveloper #TechLeadership #Microservices
To view or add a comment, sign in
-
📌 Callable vs Runnable in Java — Returning Results from Threads In multithreading, not all tasks are the same. Sometimes we need a thread to return a result. This is where Callable comes in. 1️⃣ Runnable • Introduced in Java 1.0 • Does NOT return a result • Cannot throw checked exceptions Example: Runnable task = () -> { System.out.println("Running task"); }; 2️⃣ Callable • Introduced in Java 5 • Returns a result • Can throw checked exceptions Example: Callable<Integer> task = () -> { return 10; }; 3️⃣ Using Callable with Executor ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> future = executor.submit(task); Integer result = future.get(); executor.shutdown(); 4️⃣ What Is Future? Future represents: • Result of an asynchronous computation • Allows checking if task is complete • Can retrieve result using get() 5️⃣ Key Differences Runnable: • No return value • No checked exceptions Callable: • Returns value • Throws checked exceptions • Used with Future 🧠 Key Takeaway Runnable is for fire-and-forget tasks. Callable is for tasks that produce results. Future bridges asynchronous execution with synchronous result retrieval. #Java #Multithreading #ExecutorService #Callable #Concurrency
To view or add a comment, sign in
-
Came across a newly released, well-structured resource for Java developers that’s worth sharing: 👉 https://lnkd.in/dfikH6W8 JavaEvolved is a curated collection of Java best practices, patterns, and practical examples. It’s cleanly organized and useful both for revisiting fundamentals and refining more advanced concepts. Definitely a helpful reference for anyone working with Java. ☕ #Java #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🔵 Set in Java – Collections Framework Set is an interface in the Java Collections Framework that represents a collection of unique elements. Unlike List, a Set does not allow duplicate values and focuses on maintaining uniqueness. 🔹 What is Set in Java? A Set is used when duplicate data is not allowed, such as: Unique user IDs Email addresses Roll numbers Product codes 📌 Set does not support index-based access. 🔹 Key Characteristics of Set ✔ Does not allow duplicate elements ✔ Allows at most one null value (depends on implementation) ✔ No index-based access ✔ Faster search operations ✔ Order is not guaranteed (except some implementations) 🔹 Set Hierarchy (Important) Set (Interface) HashSet LinkedHashSet SortedSet (Interface) TreeSet 🔹 Types of Set Implementations 1️⃣ HashSet ✔ No insertion order ✔ Fastest performance ✔ Uses Hashing ✔ Allows one null value 👉 Best for fast search & uniqueness 2️⃣ LinkedHashSet ✔ Maintains insertion order ✔ Slightly slower than HashSet ✔ Allows one null value 👉 Best when order + uniqueness are required 3️⃣ TreeSet ✔ Stores elements in sorted order ✔ Does not allow null values ✔ Slower than HashSet ✔ Uses Red-Black Tree 👉 Best for sorted unique data 🔹 Commonly Used Set Methods add() – Add element remove() – Remove element contains() – Check existence size() – Number of elements isEmpty() – Check empty clear() – Remove all elements TAP Academy , Rohit Ravindern, Somanna M G ,kshitij kenganavar ,Sharath R ,Ravi Magadum , Hemanth Reddy , Poovizhi VP #Java #CoreJava #JavaCollections #SetInterface #BackendDevelopment #JavaDeveloper #FullStackDeveloper #Programming #CodingLife #LearningJava #ComputerScience #SoftwareEngineering #Developers #LinkedInTech
To view or add a comment, sign in
-
-
☕ Java Generics – Upper Bounded Wildcards Explained In Java Generics, the question mark (?) represents a wildcard, meaning an unknown type. Sometimes, we need to restrict the type of objects that can be passed to a method — especially when working with numbers or specific class hierarchies. That’s where Upper Bounded Wildcards come into play. 🔹 What is an Upper Bounded Wildcard? To restrict a wildcard to a specific type or its subclasses, we use: <? extends ClassName> This means: 👉 Accept ClassName or any of its subclasses. For example, if a method should only work with numeric types, we restrict it to Number and its subclasses like Integer, Double, etc. As explained in the document (Page 1), the syntax uses ? followed by the extends keyword to define the upper bound. 🔹 Practical Example From the example shown (Page 2), a method calculates the sum of elements in a list: public static double sum(List<? extends Number> numberlist) { double sum = 0.0; for (Number n : numberlist) sum += n.doubleValue(); return sum; } 📌 Why ? extends Number? ✔ Ensures only numeric types are allowed ✔ Accepts List<Integer> ✔ Accepts List<Double> ✔ Maintains type safety 🔹 Usage in Main Method List<Integer> integerList = Arrays.asList(1, 2, 3); System.out.println("sum = " + sum(integerList)); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); System.out.println("sum = " + sum(doubleList)); 🔹 Output (Page 3) sum = 6.0 sum = 7.0 This demonstrates how the same method works seamlessly with different numeric types. 💡 Upper bounded wildcards improve flexibility while maintaining compile-time type safety. They are essential for writing reusable and robust generic methods in Java. #Java #Generics #UpperBoundedWildcards #JavaProgramming #OOP #FullStackJava #Developers #AshokIT
To view or add a comment, sign in
-
📌 Executor Framework in Java — The Right Way to Manage Threads Creating threads manually using new Thread() is not scalable for real-world applications. Java provides the Executor Framework to manage threads efficiently using thread pools. 1️⃣ Why Not Create Threads Manually? • High memory cost • Poor resource management • No reuse of threads • Difficult to control lifecycle 2️⃣ What Is Executor Framework? Introduced in: java.util.concurrent It separates: • Task submission • Thread management 3️⃣ Basic Example ExecutorService executor = Executors.newFixedThreadPool(3); executor.submit(() -> { System.out.println(Thread.currentThread().getName()); }); executor.shutdown(); 4️⃣ What Happens Internally? • A pool of threads is created • Tasks are queued • Threads are reused • Better CPU utilization 5️⃣ Types of Thread Pools • FixedThreadPool • CachedThreadPool • SingleThreadExecutor • ScheduledThreadPool 6️⃣ Why It’s Important ✔ Improves performance ✔ Controls concurrency level ✔ Prevents excessive thread creation ✔ Production-ready solution 🧠 Key Takeaway Executor Framework manages threads. You focus on tasks. It is the preferred way to handle concurrency in modern Java applications. #Java #Multithreading #ExecutorService #Concurrency #BackendDevelopment
To view or add a comment, sign in
-
Much needed! If you use Java, you should definitely check this out. You may be missing something that can make your life a lot easier.
Product Management | Al LLM for Intelligent Applications | Business Strategy | MBA | Developer Experience
java.evolved – Every old #Java pattern next to its modern replacement, side by side
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development