Append int array java

2 ways : append to an Array in Java

In this tutorial, I will be sharing different ways to append an element to an Array in Java. After the creation of the Array, its size can not be changed. The different ways to append an element to an Array are as follow:

1. Creating new Array
2. Using ArrayList

1. Creating new Array

We will create a newArray, greater than the size of the givenArray. In the below example we are adding a single element to the end of the Array.

1. If the size of the givenArray is n then the size of the newArray will be n+1.

2. Copy the elements from the givenArray to the newArray. We will be using Arrays.copyOf method.

3. Insert(add) the new element at the end of the Array.

import java.util.*; public class JavaHungry  public static void main(String args[])  
// Print the givenArray System.out.println("Given array is : "+Arrays.toString(num)); 
/* Using Arrays.copyOf(int[],int) method to create an Array of new size */ num = Arrays.copyOf(num, num.length+1); 
// Calculate the new length of the array int length = num.length; 
/* Store the new element at the end of the Array */ num[length - 1] = 12;
// Print the new Array System.out.println("New array is : "+Arrays.toString(num)); > > 

Output:
Given array is : [2, 4, 6, 8, 10]New array is : [2, 4, 6, 8, 10, 12]

2. Using ArrayList

1. Create an ArrayList from the givenArray by using the asList() method.
2. Add the element to the ArrayList using the add() method.
3. Convert the ArrayList to Array using the toArray() method.

import java.util.*; public class JavaHungry  public static void main(String args[])  // Initialize givenArray Integer[] num = 3,6,9,12,15>; 
// Print the givenArray System.out.println("Given array is : "+Arrays.toString(num)); 
/* Convert Array to ArrayList using Arrays.asList() method */ ListInteger> arrlistObj = 
 new ArrayListInteger>(Arrays.asList(num)); 
// Add new element to the ArrayList arrlistObj.add(18); 
// Convert the ArrayList to Array num = arrlistObj.toArray(num); 
// Print the new Array System.out.println("New array is : "+Arrays.toString(num)); > > 

Output:
Given array is : [3, 6, 9, 12, 15]New array is : [3, 6, 9, 12, 15, 18]

That’s all for today, please mention in comments in case you have any questions related to append an element to an Array in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Добавить целые числа в массив

Добавить целые числа в массив

  1. Использование другого массива для добавления целых чисел в массив в Java
  2. Используйте функцию add() для добавления целых чисел в массив в Java

В программировании массивы представляют собой общую структуру данных и хранят элементы аналогичного типа в непрерывной области памяти.

В этом руководстве будут рассмотрены различные способы добавления целых чисел в массив в Java.

Использование другого массива для добавления целых чисел в массив в Java

В Java мы можем редактировать элементы массива, но не можем редактировать размер массива. Однако мы можем создать массив большего размера для размещения дополнительных элементов. Этот метод неэффективен с точки зрения памяти.

Если у нас есть массив, содержащий пять элементов, и добавляем еще два элемента, мы можем создать еще один массив размером из семи элементов, содержащий исходные и дополнительные элементы.

Мы можем реализовать это в следующем коде.

public class ABC public static void main(String []args)  int[] arr1 = 2,3,5,7,8>; // array of size 5  int[] arr2 = new int[7]; // new array declared of size 7  for(int i = 0 ; i  5 ; i++)   // adding all the elements of orignal array arr1 to new array arr2  arr2[i] = arr1[i];  >  arr2[5] = 10; // added value 10 to 6th element of new array  arr2[6] = 12; // added value 12 to 7th element of new array  System.out.print(arr2[6]); // printing element at index 6  > > 

В приведенном выше коде мы создали arr2 , который содержит все arr1 и новые дополнительные целые числа.

Используйте функцию add() для добавления целых чисел в массив в Java

Функция add() в Java может добавлять элементы в разные коллекции, такие как списки и наборы, но не для массивов, потому что они имеют фиксированную длину, и мы не можем изменить их размер. Однако мы можем использовать эту функцию для добавления элементов, создав список массивов.

ArrayList имеет несколько преимуществ перед массивами, поскольку нет ограничений на размер списка. Мы можем бесконечно добавлять элементы в списки. Однако это не так быстро, как массивы.

import java.util.ArrayList; public class ABC public static void main(String []args)  int[] arr = 2,4,5,6>; // created an array of size = 4  // creating an ArrayList  ArrayListInteger> al = new ArrayListInteger>();  for(int x: arr)   al.add(x); // adding each element to ArrayList  >  al.add(10); // now we can add more elements to the array list  al.add(18);  System.out.print(al); > > 

Обратите внимание, что для работы с ArrayList необходимо импортировать пакет java.util.ArrayList .

Сопутствующая статья — Java Array

Источник

Java – Append to Array

In Java, an array is a collection of fixed size. You cannot increase or decrease its size. But, you can always create a new one with specific size.

To append element(s) to array in Java, create a new array with required size, which is more than the original array. Now, add the original array elements and element(s) you would like to append to this new array.

Also, you can take help of Arrays class or ArrayList to append element(s) to array. But, these techniques require conversion from array to ArrayList, and vice versa.

In this tutorial, we will go through different approaches with the examples, to append one or more elements to the given array.

Append Element to Array

In this example, we will add an element to array.

We shall implement the following steps.

  1. Take original array arr . (We shall initialize an array with some elements.)
  2. Take the element you would to append to array arr .
  3. Create new array arrNew with size greater than that of arr by one.
  4. Assign elements of arr and element to arrNew . We will use for loop to assign elements of arr to arrNew .

Java Program

public class Example < public static void main(String[] args) < String arr[] = ; String element = "mango"; String arrNew[] = new String[arr.length + 1]; int i; for(i = 0; i < arr.length; i++) < arrNew[i] = arr[i]; >arrNew[i] = element; //print new array for(String s: arrNew) < System.out.println(s); >> >
apple banana cherry mango

Append Array to Array

In this example, we will add an array to another array and create a new array.

We shall implement the following steps.

  1. Take two input arrays arr1 and arr2.
  2. Create new array arrNew with size equal to sum of lengths of arr1 and arr2.
  3. Assign elements of arr1 and arr2 to arrNew. Use for loop to assign elements of input arrays to new array.

Java Program

public class Example < public static void main(String[] args) < String arr1[] = ; String arr2[] = ; String arrNew[] = new String[arr1.length + arr2.length]; int i; for(i = 0; i < arr1.length; i++) < arrNew[i] = arr1[i]; >for(i = 0; i < arr2.length; i++) < arrNew[arr1.length + i] = arr2[i]; >//print new array for(String s: arrNew) < System.out.println(s); >> >
apple banana cherry mango grape

Append Element to Array using ArrayList

In this example, we will take help of ArrayList to append an element to array.

We shall implement the following steps.

  1. Take input array arr1.
  2. Create an ArrayList with elements of arr1.
  3. Append the element to the ArrayList.
  4. Convert ArrayList to array.

Java Program

import java.util.ArrayList; public class Example < public static void main(String[] args) < String arr[] = ; String element = "mango"; ArrayList arrayList = new ArrayList(); for(String s: arr) arrayList.add(s); arrayList.add(element); String arrNew[] = new String[arr.length + 1]; for(int i = 0; i < arrNew.length; i++) arrNew[i] = arrayList.get(i); //print new array for(String s: arrNew) System.out.println(s); >>
apple banana cherry mango

Append Element to Array using java.util.Arrays

In this example, we will use java.util.Arrays class to append an element to array.

We shall implement the following steps.

  1. Take input array arr1.
  2. Create a new array using java.util.Arrays with the contents of arr1 and new size.
  3. Assign the element to the new array.

Java Program

import java.util.Arrays; public class Example < public static void main(String[] args) < String arr[] = ; String element = "mango"; String arrNew[] = Arrays.copyOf(arr, arr.length + 1); arrNew[arr.length]= element; //print new array for(String s: arrNew) System.out.println(s); > >
apple banana cherry mango

Conclusion

In this Java Tutorial, we have learned how to append element(s) to array using different techniques with the help of example programs.

Источник

Append int array 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

Источник

Читайте также:  Android java class oncreate
Оцените статью