Add Object to Arraylist at Specified Index

Add object to ArrayList at specified index

You can do it like this:

list.add(1, object1)
list.add(2, object3)
list.add(2, object2)

After you add object2 to position 2, it will move object3 to position 3.

If you want object3 to be at position3 all the time I'd suggest you use a HashMap with position as key and object as a value.

How to insert an object in an ArrayList at a specific position

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)

This method replaces the element at the specified position in the
list with the specified element, and returns the element previously
at the specified position.

Adding and setting new object in ArrayList at specific index (JAVA)

First create POJO Class, here is Company

package com.appkart.array;

public class Company {

private String name;
private String id;
private String city;
private String state;

public Company(String name, String id, String city, String state) {
this.name = name;
this.id = id;
this.city = city;
this.state = state;

}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

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

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

@Override
public String toString() {
return name + ", " + id + ", " + city + ", " + state;
}
}

Then now add company into Arraylist as

package com.appkart.array;

import java.util.ArrayList;

public class TestCompany {
ArrayList<Company> companies = new ArrayList<Company>();

public void addCompany() {
Company newYorkTimes = new Company("New York Times", "1234",
"New York", "NY");
Company nbc = new Company("NBCPhiladelphia", "X123", "Philadelphia",
"PA");
Company fox = new Company("FOX News", "0987", "Los Angeles", "LA");

companies.add(newYorkTimes);
companies.add(nbc);
companies.add(fox);

printCompanyInfo();
}

public void addCompanyAtIndex(int index, Company company) {
companies.add(index, company);

printCompanyInfo();
}

public void printCompanyInfo() {
for (Company company : companies) {
System.out.println(company.toString());
}
}

public static void main(String[] args) {
TestCompany testCompany = new TestCompany();
testCompany.addCompany();

Company company = new Company("CNN", "1230", "Atlanta", "GA");
testCompany.addCompanyAtIndex(1, company);
}
}

Why cannot insert element into ArrayList at specific index?

The capacity of an ArrayList is the number of elements in the array used to store list elements.

The size of an ArrayList is the number of elements in the list.

You can only add() elements at indexes ranging from zero to size, so if the current size is zero, you can only specify an index of zero.

However, the array that backs the list will not have to be replaced until the size exceeds the original capacity.


Collections objects enforce contracts to maintain invariants for the state of the collection. In this case, lists ensure that an element at an index can be read only if it was explicitly added to the list. If you could skip index 0 and add an element at index 1, what should happen if you get index 0? Return null? Throw NoSuchElementException? A primary difference between an ArrayList and an Object[] is that the list constrains use of the array to provide well-defined behavior.

error when add element at specified index in ArrayList [Java]

The reason why it's always in index 0 has nothing to do with whether you pass an index or not.

while (true){
String option = in.nextLine() ;
if(!"6".equals(option)) {
if ("2a".equals(option)) { // Define new department
...
List<Department> departmentList;
//here create a new arrayList
departmentList = new ArrayList<>();
//try to add element without index
// departmentList.add(Department_Name);
//try to add element with index
departmentList.add(d, Department_Name);
d++ ;
....

}
}

Each time you add an element, you add it in a newly created List. You should create the List before your loop, and just keep the add statements in there:

List<Department> departmentList = new ArrayList<>();
while (true){
String option = in.nextLine() ;
if(!"6".equals(option)) {
if ("2a".equals(option)) { // Define new department
...
//try to add element without index
// departmentList.add(Department_Name);
//try to add element with index
departmentList.add(d, Department_Name);
d++ ;
....

}
}

ArrayList's add(index,object) method throw IndexOutOfBoundException

The purpose of having an internal array with a size greater then List.size() is to avoid re-allocating the array unnecessarily. If the internal array always had the same size as the List, then every time a new element is added, the internal array would have to be re-allocated, causing a performance penalty.

How to insert an item into an array at a specific index (JavaScript)

You want the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge


Related Topics



Leave a reply



Submit