Как в массив добавить элемент java

Как в массив добавить элемент java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

How To Add Elements To An Array In Java

The arrays in Java are of fixed size i.e. once declared you cannot change their size. So when there is a requirement to add a new element to the array, you can follow any of the approaches given below.

  • Using a new array larger than the original to add a new element.
  • Using ArrayList as an intermediate structure.
  • Shifting the elements to accommodate the new element.

Add an element to an Array in Java

Java Add To Array – Adding Elements To An Array

In this tutorial, we will discuss all the above three methods for adding an element to the array.

Use A New Array To Accommodate The Original Array And New Element

In this approach, you will create a new array with a size more than the original array. For example, if the original array size is N, you will create a new array with size N+1 in case you want to add one element.

Once a new array is created, you can copy the original array of N elements into the new array. Then add the new element at (N+1) th location.

The program to add an element with the above approach is given below.

import java.util.*; class Main < // Function to add x in arr public static int[] add_element(int n, int myarray[], int ele) < int i; int newArray[] = new int[n + 1]; //copy original array into new array for (i = 0; i < n; i++) newArray[i] = myarray[i]; //add element to the new array newArray[n] = ele; returnnewArray; >public static void main(String[] args) < int n = 5; int i; // Original array with size 5 int myArray[] = < 1, 3, 5, 7, 9 >; System.out.println("Original Array:\n" + Arrays.toString(myArray)); //new element to be added to array int ele = 11; myArray = add_element(n, myArray, ele); System.out.println("\nArray after adding " + ele + ":\n" + Arrays.toString(myArray)); > >

Use a new array to accommodate the original array and new element

In this technique, you simply create a new array larger than the original by one element. You copy all the elements of the original array to the new array and then insert a new element at the end of the new array.

Читайте также:  Print yes if python

This is a traditional method that is quite slow and not that efficient.

Use ArrayList As An Intermediate Structure

ArrayList is a data structure that is dynamic in nature. Hence you can dynamically increase the size of the array list and add as many elements to it. Thus you can use ArrayList as an intermediate structure while adding elements to the array

For adding an element to the array,

  • First, you can convert array to ArrayList using ‘asList ()’ method of ArrayList.
  • Add an element to the ArrayList using the ‘add’ method.
  • Convert the ArrayList back to the array using the ‘toArray()’ method.

Let’s put these steps into an implementation.

import java.util.*; class Main < public static void main(String[] args) < // Original array with size 5 Integer odd_Array[] = < 1,3,5,7,9 >; // display the original array System.out.println("Original Array:" + Arrays.toString(odd_Array)); // element to be added int val = 11; // convert array to Arraylist List<Integer>oddlist = new ArrayList<Integer>(Arrays.asList(odd_Array)); // Add the new element oddlist.add(val); // Convert the Arraylist back to array odd_Array = oddlist.toArray(odd_Array); // display the updated array System.out.println("\nArray after adding element " + val + ":" + Arrays.toString(odd_Array)); > >

Use ArrayList as an intermediate structure

The above program shows an array of odd numbers. It is converted to ArrayList. Then another odd number is added to this list. Next, the ArrayList is converted back to the array and an updated array is displayed.

Shifting The Elements To Accommodate The New Element

The above two methods of adding an element to the array dealt with elements being added at the end of the array. So these methods were rather easy to implement. But what about the case wherein you need to add an element at a specific position?

Читайте также:  My first html project

In this case, the implementation is a little tough.

Let’s list the sequence of steps.

  • Create a new destination array with a size more than the original array.
  • Then copy the elements from the original array before the specified index to the new array.
  • Shift the elements after the index to the right by one position so that you create a space for the new element.
  • Insert a new element at the specified index in the destination array.

The following program implements this technique.

importjava.util.*; class Main < public static void main(String[] args) < // Original array with size 5 Integer odd_Array[] = < 1,3,7,9,11 >; // display the original array System.out.println("Original Array:" + Arrays.toString(odd_Array)); // element to be added at index int val = 5; int index = 2; //dest array with size more than 1 of the original array int[] dest_Array = new int[odd_Array.length+1]; int j = 0; //Iterate dest_array and insert new element as well as shift other elements to the right for(int i = 0; i <dest_Array.length; i++) < if(i == index) < dest_Array[i] = val; >else < dest_Array[i] = odd_Array[j]; j++; >> // display the updated array System.out.println("\nArray after adding element " + val + " at index " + index +":" + Arrays.toString(dest_Array)); > >

Shifting the elements to accommodate the new element

Here given an array of odd numbers, we need to insert number 5 at position (index) 2 in the array. To do this, we create another destination array with the size as one more than that of the original array. Now over a loop, we shift the original array elements to the new array till we reach the index where the new element is to be added.

We add the new element at index 2 in the new array. Then starting from index 2, we copy all the other elements from the old array to the new array by shifting their indices by 1 to the right.

Frequently Asked Questions

Q #1) Can we increase the size of the array in Java?

Answer: No. We cannot increase the size of the array in Java once it is instantiated. If at all you need a different size for the array, create a new array and move all the elements to the new array or use an ArrayList which dynamically changes its size.

Читайте также:  Php query source server

Q #2) How do you add two arrays in Java?

Answer: You can either add two arrays or form a resultant array manually by using for loop. Or you can use the arrayCopy method to copy one array into another. For both the techniques, create a resultant array with enough room to accommodate both the arrays.

Q #3) How do you add an ArrayList to an Array in Java?

Answer: Create a list of n items. Then use the toArray method of the list to convert it to the array.

Q #4) What is a growable array in Java?

Answer: A growable array is simply a dynamic array which increases its size when more items are added to it. In Java, this is an ArrayList.

Q #5) Can you declare an array without assigning the size of an array?

Answer: No. Array size must be declared before using it. If not, it results in a compilation error.

Q #6) Can you add multiple elements to an Array at once?

Answer: No. You cannot add only one element to an array at a given instant. If you want to add multiple elements to the array at once, you can think of initializing the array with multiple elements or convert the array to ArrayList. ArrayList has an ‘addAll’ method that can add multiple elements to the ArrayList.

Conclusion

Adding a new element to the array can be done using three techniques. The first technique is less efficient wherein we just create a new array with increased size and then copy the elements from earlier array into it and then add the new element.

The most efficient one is using ArrayList to add a new element. We just convert the array to the ArrayList and then add the element to the list. Then we convert the ArrayList back to the array.

These techniques only take care of adding an element at the end of the list. If we want to add an element in between the array at a specified index, then we need to shift the elements after the specified index to the right by one position and then accommodate the new element.

We have seen all these three techniques with examples in this tutorial. We will discuss some more array operations in our subsequent tutorials.

Источник

Оцените статью