How to increase the size of an array in Java? - java

I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.

Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.

On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.

You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.

You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.

By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e

https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);

u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml

Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])

u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}

public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}

Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.

Related

How to print additional arrays? [duplicate]

I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.
Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.
By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);
u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.

Convert a string into a multidimensional arrays with different lengths

I need to execute by command line a code that will provide a multidimensional array with elements with not necessarily equal lengths.
The execution string is bellow:
start /wait java -jar testMSMWithIndex.jar Foursquare_weather_day_root-type_type 0,1,2-4
I'm considering to pass the parameter 0,1,2-4 and then convert it in a multidimensional array with elements of different lengths in this case, i.e. {{0}, {1}, {2, 4}}.
Note that {{0, null}, {1, null}, {2, 4}} does not work to my problem.
Do you guys know how to develop a method or even get directly as an array from args?
I really appreciate any help you can provide.
It's doubtful that anything already exists to do this for you, so you'll have to parse the string for yourself. Something like this would do it:
public static int[][] parseRaggedArrayFromString(String s)
throws NumberFormatException {
String[] ss = s.split(",");
int[][] result = new int[ss.length][];
for (int i = 0; i < ss.length; ++i) {
if (!ss[i].contains("-")) {
result[i] = new int[1];
result[i][0] = Integer.parseInt(ss[i]);
} else {
String[] range = ss[i].split("-", 2);
int lo = Integer.parseInt(range[0]);
int hi = Integer.parseInt(range[1]);
int size = hi - lo + 1;
result[i] = new int[size > 0 ? size : 1];
int j = 0;
do {
result[i][j] = lo;
++lo;
++j;
} while (lo <= hi);
}
}
return result;
}
It's basically a split on , and -. From there is just handling the data. Comments in the code.
/**
* #author sedj601
*/
public class Main {
public static void main(String[] args) {
String input = "0,1,2-3";
String[] firstArray = input.split(",");//Split on ,.
String[][] outputArray = new String[firstArray.length][];//The array that will be holding the output
//Used to process the firstArray
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i].length() > 1) {//If the lenght is greater than one. split on -.
String[] secondArray = firstArray[i].split("-");
//Subtract the two numbers and add one to get the lenght of the array that will hold these values
int arrayLength = Integer.parseInt(secondArray[1]) - Integer.parseInt(secondArray[0]) + 1;
String[] tempArray = new String[arrayLength];
int increment = 0;//Keeps up with the tempArray index.
//loop from the first number to the last number inclusively.
for (int t = Integer.parseInt(secondArray[0]); t <= Integer.parseInt(secondArray[1]); t++) {
tempArray[increment++] = Integer.toString(t);//Add the data to the array.
}
outputArray[i] = tempArray;//Add the array to the output array.
} else {//If the lenght is 1, creat an array and add the current data.
String[] tempArray = new String[1];
tempArray[0] = firstArray[i];
outputArray[i] = tempArray;
}
}
//Print the output.
for (String[] x : outputArray) {
for (String y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Output:
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
0
1
2 3
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.194 s
Finished at: 2021-01-08T00:08:15-06:00
------------------------------------------------------------------------
I really think that's possible when you create an array of type Object .(not a good idea) Since multi-D arrays can only hold arrays of same length (int[][]). Then you create and retrieve values from array by casting...
I am trying here to be creative and adopt to your requirements..
public class x {
public static void main(String[] args) {
Object[] arguments = new Object[args.length];
// Then make a loop to capture arguments in array..
// or add manually
arguments[0] = new String[]{args[0]};
arguments[1] = new String[]{args[1],args[2]};
//Then retrieve info from object later by casting
System.out.println(java.util.Arrays.toString((String[]) arguments[1]));
}
}
...
Although, please consider using a collection...
While I waited for the answer, I found a way to solve the problem.
The relevant information here is that we do not need to set the second array dimension in its instantiation.
The code is below:
// INPUT string = "2-3,1,4-5"
private static String[][] featuresConversion(String string) {
String[] firstLevel = string.split(","); // 1st lvl separator
String[][] features = new String[firstLevel.length][]; // Sets 1st lvl length only
int i = 0;
for (String element : firstLevel) {
features[i++] = element.split("-");
}
return features;
}
I want to thank you all. All suggested solutions also work fine!

How to create an array from the contents of a text file to be sorted?

This is a program that takes these three arrays and sorts them using insertion sort and counting the number of comparisons and swaps performed for each array when sorted.
I'm now trying to test three other arrays that have been made on text files. The these three text files are just lists of numbers, the first text file is called "array4.txt" and its list of numbers contains 1 through 2000 in order.
The second file is called "array5.txt" and its list of numbers contains 2000 through 1 in descending order. Lastly, the third file is called "array6.txt" and its list of numbers contains a list of randomly mixed numbers from 1 to 2000, including 1 and 2000 with no repeats.
My goal is to read these files and put their values into an actual array and for my insertion sort method to read them, sort them, and count the number of comparisons and exchanges just as what I did with my first three arrays.
I'm very new to Java and don't know exactly how to do this.
import java.util.Scanner;
import java.io.*;
public class InsertionSort
{
public static void main(String args[]) throws IOException
{
int[] Array = {1,2,3,4,5,6,7,8,9,10};
int[] Array2 = {10,9,8,7,6,5,4,3,2,1};
int[] Array3 = {1,10,2,9,3,8,4,7,5,6};
System.out.println("Insertion Sort: ");
System.out.println();
System.out.println("Best Case Scenario: ");
printArray(Array);
insertionSort(Array);
System.out.println("Worst Case Scenario: ");
printArray(Array2);
insertionSort(Array2);
System.out.println("Average Case Scenario: ");
printArray(Array3);
insertionSort(Array3);
}
public static void insertionSort(int[] list)
{
int comps = 0, swaps = 0;
for(int i = 1; i < list .length; i++) {
int j = i;
// compare i with sorted elements and insert it
// sorted elements: [0..i-1]
while (j > 0 && list[j] < list[j - 1]) {
int temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
swaps++;
comps++; // loop condition true
j--;
}
comps++; // checking loop condition when false
}
//printArray(list);
System.out.println("Comparisons: " + comps
+ " Swaps: " + swaps);
System.out.println();
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
}
This is what I came up with. Hope it helps!
package com.company;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Replace array.txt with the name of your txt file and your path
Scanner fileScanner = new Scanner(new File("array.txt"));
// Counter variable so we'll know the size of the array we'll need
int counter = 0;
// Iterate through the file counting the number of integers and incrementing the counter variable
while(fileScanner.hasNextInt()){
counter++;
fileScanner.nextInt();
}
// Reset the scanner to the beginning of the txt file
fileScanner = new Scanner(new File("array.txt"));
// Scan each integer into the array
int [] array = new int[counter];
for (int i = 0; i < array.length; ++i) array[i] = fileScanner.nextInt();
}
}
Here you go:
public void getIt() {
List<Integer> ints = new ArrayList(); //temporary holder
try (Scanner scanner = new Scanner("filename.txt")) { //open a scanner that will scan our file
scanner.forEachRemaining(line -> { //iterate through each line in our file
String[] numberStrings = line.split(","); // the comma is your presumed delimeter IF one exists
for (int x = 0; x < numberStrings.length; x++) { // loop through each item separated by a comma on each line
ints.add(Integer.parseInt(numberStrings[x])); // turn this string into an int and add it to your list
}
});
}
Integer[] integerArray = ints.toArray(new Integer[ints.size()]); //transform our list into an array
}
If it's only one number per line you don't need the for loop or the line.split inside of the forEachRemaining

Java: Filling an array with random numbers without duplicates [duplicate]

so my program is supposed to access a text document then do all that jazz that currently works. The only problem that I can't figure out is how to shuffle the contents of an array without having them end up on top of each other. Both internets and multiple tries with random and for loops have been unfruitful. here is my code:
import java.io.*;
import java.util.*;
public class lab_6 {
public static void main(String[] args)throws FileNotFoundException {
Scanner input = new Scanner(System.in); //reads from keyboard
System.out.println("What is the name of your file. ");
String name = input.nextLine();
Scanner reader = new Scanner(new File(name));// Open text file
System.out.println("how many names are in your array");
int num = input.nextInt();
String[] names = new String[num];
for (int index = 0; index< names.length; index++)
{
names[index] = reader.nextLine();// Gets a line while there is one
}
System.out.println("\nOriginal List");
printList(names);
System.out.println("\nShuffled List");
shuffle(names);
printList(names);
System.out.println("\nSorted List");
Arrays.sort(names); // this is a built in method
printList(names);
System.out.println("What name are you looking for");
Scanner input1 = new Scanner(System.in); //reads from keyboard
String find = input1.nextLine();
int index = search(names,find);
if(index == -1)
System.out.println("The name was not there");
else
System.out.println(find+" was found at position "+index);
System.out.println("The average length of all the names is "+averageLength(names));
}
public static void printList(String[] array) // print the list of names numbered
{
for (int i=0; i<array.length; i++)
{
System.out.println((i+1)+") "+ array[i]);
}
}
public static void shuffle (String[] array) // mix-up the array
{
}
public static int search(String[] array, String find)
{
for(int i=0; i<array.length; i++) {
if (array[i].equals(find) ) return i;
}
return -1;
}
public static double averageLength(String[] array) //return the average length of the names
{
int sum=0;
for (int i=0; i<array.length; i++)
{
int l= array[i].length();
sum +=l;
}
int average = sum/(array.length);
return average;
}
}
String[] names = ...;
Collections.shuffle(Arrays.asList(names));
// done
Note that Arrays.asList() returns a modifiable (but fixed-length) list, backed by the array, and not a copy of the array. So the array will be shuffled.
Just use the Fisher-Yates shuffle (Knuth algorithm P):
private Random rand = new Random();
public static void shuffle(String[] array) { // mix-up the array
for (int i = array.length - 1; i > 0; --i) {
int j = rand.nextInt(i + 1);
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
See:
Knuth, D. 1969, 1998: Seminumerical Algorithms 1st & 3rd Eds. The Art of Computer Programming Series, Volume 2, p. 125.
Fisher, Ronald A.; Yates, Frank (1948) [1938]. Statistical tables for biological, agricultural and medical research (3rd ed.). London: Oliver & Boyd. pp. 26–27.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
https://stackoverflow.com/a/1520212/636009
You can use the Collections class, with the shuffle method. The documentation is available here.
Example
int[] values = {1,2,3,4,5};
List<Integer> valuesList = Arrays.asList(values);
Collections.shuffle(valuesList);
// valuesList is shuffled.

java get the number of array values

I already have the following code
public class Qn3
{
static BigDecimal[] accbal= new BigDecimal[20];
private static Integer[] accnums = new Integer[5];
public static void main(String[] args)
{
int count;
accnums = {1,2} //i cant add this line of code as well, what is wrong?
while(accnums.length < 5)
{
count = accnums.number_of_filled_up_indexes
//this is not actual code i know
//do this as the number of values in the array are less than 5
break;
}
//do this as number of values in the array are more than 5
}
}
I must use this code there is no changing this is a requirment, so please dont suggest to use arraylist and such (i am aware of other array types and methods)
The problem is that as I have already declared that accnums must contain only 5 values, that is predefined.
I am trying to perform a check whether the ones that are not null and if all are null. To do this I have tried this but this is giving me 5 p(pre-defined integer array value not what I want).
public static void main(String[] args)
{
int count = 0;
accnums = new Integer[] {1,2,null,null,null};
for (int index = 0; index < accnums.length; index++)
{
if(accnums[index] != null)
{
count++;
}
}
System.out.println("You have used " + count + " slots);
}
Try this...
accnums[0] = new Integer(1);
accnums[1] = new Integer(2);
Both the below will work if done during Declaration and Initializing time of and array.
Integer[] arr = new Integer[]{1,2,3};
Integer[] arr = {1,2,3}
But when you just declare the array as
Integer[] arr = new Integer[3]; // Still array holds no Object Reference Variable
then later initialize it this way...
arr = new Integer{1,2,3,}; // At this time it hold the ORV
Array are always initialized whether used at class or method scope, so for an int array all the values will be set to default as 0, and for Integer it will be null, as its an Wrapper object.
Eg:
Integer[] arr = new Integer[5];
arr[0] = 1;
arr[1] = 2;
System.out.println(arr.length);
for (Integer i : arr){
if (i!=null){
count++;
}
}
System.out.println("Total Index with Non Null Count :"+count);
}
accnums[0] = 1;
accnums[1] = 2;
final int count = accnums.length
- Collections.frequency(Arrays.asList(accnums), null);
System.out.println("You have used " + count + " slots");
or, if you really must do it manually...
int count;
for (final Integer val : accnums) {
if (val != null) {
++count;
}
}

Categories

Resources