Monday, 29 November 2021

How to get the capacity of ArrayList in Java?

‘size’ specifies number of elements in the list, whereas capacity specifies how many elements the list can accommodate.

 

For example,

List<Integer> list = new ArrayList<> (10);

 

Above statement defines an ArrayList of capacity 10 and size 0.

 


Let’s add one element to ArrayList.

 

list.add(23);

 

When you add one element to the list, size becomes 1 and capacity becomes 10.


What if you are inserting more elements greater than list capacity?

A new Array with more capacity is created to allocate more elements. All the existing elements of list are copied to new array (List is backed by an array).

 

As you understand the difference between size and capacity, let me explain how to get the capacity of an ArrayList. When I see the Java documentation, I do not see any method to get the capacity of ArrayList..But do not worry, we can get the capacity using reflections.

 

As per the Java documentation, Java use the field ‘elementData’ to store the list elements. By calculating this array size, we can get the capacity of ArrayList.

 

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 * will be expanded to DEFAULT_CAPACITY when the first element is added.
 */
transient Object[] elementData;

 

Below snippet, is used to get the capacity of ArrayList.

private static Field capacityField;

static {
	setAccessibilityToCapacity();
}

private static void setAccessibilityToCapacity() {
	try {
		capacityField = ArrayList.class.getDeclaredField("elementData");
		capacityField.setAccessible(true);
	} catch (Exception e) {
		throw new ExceptionInInitializerError(e);
	}
}

@SuppressWarnings("unchecked")
public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {
	try {
		final E[] elementData = (E[]) capacityField.get(arrayList);
		return elementData.length;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}

}

Find the below working application.

 

ArrayListCapacity1.java

package com.sample.app.collections;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class ArrayListCapacity1 {

	private static Field capacityField;

	static {
		setAccessibilityToCapacity();
	}

	private static void setAccessibilityToCapacity() {
		try {
			capacityField = ArrayList.class.getDeclaredField("elementData");
			capacityField.setAccessible(true);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	@SuppressWarnings("unchecked")
	public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {
		try {
			final E[] elementData = (E[]) capacityField.get(arrayList);
			return elementData.length;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public static void main(String args[]) {
		ArrayList<Integer> arrayList = new ArrayList<>(10);

		System.out.println("size -> " + arrayList.size());
		System.out.println("capacity -> " + getArrayListCapacity(arrayList));

		System.out.println("\nAdd two elements to the list\n");
		arrayList.add(10);
		arrayList.add(11);

		System.out.println("\nsize -> " + arrayList.size());
		System.out.println("capacity -> " + getArrayListCapacity(arrayList));

		System.out.println("\nAdd 10 more elements to the list\n");
		for (int i = 0; i < 10; i++) {
			arrayList.add(i);
		}

		System.out.println("\nsize -> " + arrayList.size());
		System.out.println("capacity -> " + getArrayListCapacity(arrayList));

	}

}

Output

size -> 0
capacity -> 0

Add two elements to the list


size -> 2
capacity -> 10

Add 10 more elements to the list


size -> 12
capacity -> 15 

 

 

 


 

 

 

 

 

 

 

You may like

Interview Questions

Java: Get all the indexes of occurrence of a substring

Java: How to replace a value in ArrayList or LinkedList

Why do we declare logger with static and final?

How to check the type of a variable in Java?

Set a system property in command line

Java: Convert ASCII code to equivalent character

ASCII stands for American Standard Code for Information Interchange, is a character encoding standard for electronic communication.

 

By explicitly casting the integer to a character, we can get the ASCII equivalent of given integer.

 

char ch = (char)i;

 

AsciiCharDemo1.java

package com.sample.app.chars;

public class AsciiCharDemo1 {
	
	private static char printAsciiChar(int i) {
		char ch = (char)i;
		return ch;
	}
	
	public static void main(String args[]) {
		System.out.println("Ascii associated with number 65 is : " + printAsciiChar(65));
	}

}

Output

Ascii associated with number 65 is : A

You may like



 

 

FastAPI: Deprecate a query parameter

By setting the ‘deprecated’ argument of Query function to True, we can specify that this parameter is going to be deprecated in future.

 

deprecateQueryParam.py

from fastapi import FastAPI, Query
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

@app.get("/products")
def productInfo(
    infoLevel : str,
    formatType : str = Query('JSON', min_length=2, deprecated=True),
    productId: str = Query(
        ...,
        min_length = 4, 
        max_length=50,  
        title='Product id',
        description = "Enter valid product id"
        ), 
    noOfItems : Optional[int] = Query(None, gt = 0, lt = 50, title='Number of items to return')
):
    return {
        'productId' : productId, 
        'noOfItems' : noOfItems, 
        'infoLevel' : infoLevel, 
        'formatType' : formatType
    }

 

Open terminal and execute the command ‘uvicorn deprecateQueryParam:app --reload’.

$uvicorn deprecateQueryParam:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [93386] using statreload
INFO:     Started server process [93390]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:54262 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:54262 - "GET /openapi.json HTTP/1.1" 200 OK

Open the url ‘http://127.0.0.1:8000/docs’ in browser.


 

Now, you can see that formatType is deprecated.

 

 

  

Previous                                                    Next                                                    Home

Spring Data: ArangoDB: events

Spring Data ArangoDB supports several ApplicationEvent events. You can register to these events in your application and respond accordingly.

 

How to listen on events?

It is very simple, create a spring bean by extending AbstractArangoEventListener class.

@Component
public class EmployeeListener extends AbstractArangoEventListener<Employee> {
  public void onBeforeSave(final BeforeSaveEvent<Employee> event) {
    System.out.println("Before saving : " + event.getSource());
  }

  public void onAfterSave(final AfterSaveEvent<Employee> event) {
    System.out.println("After saving : " + event.getSource());
  }

  public void onBeforeDelete(final BeforeDeleteEvent<Employee> event) {
    System.out.println("Before deleting : " + event.getSource());
  }

  public void onAfterDelete(final AfterDeleteEvent<Employee> event) {
    System.out.println("After deleting : " + event.getSource());
  }

}

 

Find the below working application.

 

Step 1: Create new maven project ‘event-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>event-demo</artifactId>
  <version>1</version>

  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
  </parent>


  <dependencies>
    <dependency>
      <groupId>com.arangodb</groupId>
      <artifactId>arangodb-spring-boot-starter</artifactId>
      <version>2.3.3.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

 

Step 3: Define Employee entity class.

 

Employee.java

package com.sample.app.entity;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;
import com.arangodb.springframework.annotation.PersistentIndex;

import org.springframework.data.annotation.Id;

@Document("employees")
@PersistentIndex(fields = { "age" })
public class Employee {

  @Id // db document field: _key
  private String key;

  @ArangoId // db document field: _id
  private String arangoId;

  private Integer id;
  private String firstName;
  private String lastName;
  private Integer age;

  public Employee() {

  }

  public Employee(Integer id, String firstName, String lastName, Integer age) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getArangoId() {
    return arangoId;
  }

  public void setArangoId(String arangoId) {
    this.arangoId = arangoId;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "Employee [key=" + key + ", arangoId=" + arangoId + ", id=" + id + ", firstName=" + firstName
        + ", lastName=" + lastName + ", age=" + age + "]";
  }

}

 

Step 4: Define Employee repository interface.

 

EmployeeRepository.java

package com.sample.app.repository;

import com.arangodb.springframework.repository.ArangoRepository;
import com.sample.app.entity.Employee;

public interface EmployeeRepository extends ArangoRepository<Employee, String> {

}

 

Step 5: Define arango db configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
  }

  @Override
  public String database() {
    return "abc_org";
  }
}

Step 6: Define EmployeeListener bean.

 

EmployeeListener.java

package com.sample.app.listener;

import org.springframework.stereotype.Component;

import com.arangodb.springframework.core.mapping.event.AbstractArangoEventListener;
import com.arangodb.springframework.core.mapping.event.AfterDeleteEvent;
import com.arangodb.springframework.core.mapping.event.AfterSaveEvent;
import com.arangodb.springframework.core.mapping.event.BeforeDeleteEvent;
import com.arangodb.springframework.core.mapping.event.BeforeSaveEvent;
import com.sample.app.entity.Employee;

@Component
public class EmployeeListener extends AbstractArangoEventListener<Employee> {
  public void onBeforeSave(final BeforeSaveEvent<Employee> event) {
    System.out.println("Before saving : " + event.getSource());
  }

  public void onAfterSave(final AfterSaveEvent<Employee> event) {
    System.out.println("After saving : " + event.getSource());
  }

  public void onBeforeDelete(final BeforeDeleteEvent<Employee> event) {
    System.out.println("Before deleting : " + event.getSource());
  }

  public void onAfterDelete(final AfterDeleteEvent<Employee> event) {
    System.out.println("After deleting : " + event.getSource());
  }

}

Step 7: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
  public static void main(String args[]) {
    SpringApplication.run(App.class, args);
  }

  @Bean
  public CommandLineRunner demo(EmployeeRepository employeeRepo) {

    return (args) -> {
      Employee emp1 = new Employee(1, "Ram", "Gurram", 31);

      System.out.println("Saving employee");
      emp1 = employeeRepo.save(emp1);
      
      System.out.println("\nDeleting employee");
      employeeRepo.deleteById(emp1.getArangoId());
    };
  }
}

Total project structure looks like below.



Run App.java, you will see below messages in console.

Saving employee
Before saving : Employee [key=null, arangoId=null, id=1, firstName=Ram, lastName=Gurram, age=31]
After saving : Employee [key=4098, arangoId=employees/4098, id=1, firstName=Ram, lastName=Gurram, age=31]

Deleting employee
Before deleting : employees/4098
After deleting : employees/4098

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/event-demo




 

 

 

Previous                                                    Next                                                    Home