Kalle Alanen
Kalle Alanen

Reputation: 31

Growing array of primitives in java

I am learning Android and at the same time boosting my efficiency know-how. I am writing a password generator that generates a random password from a set of characters selected using specific rules. I have an array where I am planning to store the characters. The array begins at a size of X, which is the amount of possible character in all cases. I then add up to three times additional sets of characters to the array. Since I can't resize the array, I would have to copy and recreate it larger every time with a copy loop or ArrayCopy or similar.

Should I do that or switch to for example ArrayList? Sure, neither will in real life be problems as there will be about 70 characters in total, but I am interested in it as a practice.

Thanks to all.

pseudocode:

initialize array  
add first set  
if adding second set  
    add second set  
if adding third set  
    add third set  
if adding fourth set  
    add fourth set  
return array

Upvotes: 0

Views: 617

Answers (3)

sauv0168
sauv0168

Reputation: 83

You can use ArrayList as it is automatically resized when you add or remove items.

import java.util.*;

public class ArrayListDemo {
public static void main(String args[]) {
  // create an array list
  ArrayList al = new ArrayList();
  System.out.println("Initial size of al: " + al.size());

  // add elements to the array list
  al.add("C");
  al.add("A");
  al.add("E");
  al.add("B");
  al.add("D");
  al.add("F");
  al.add(1, "A2");
  System.out.println("Size of al after additions: " + al.size());

  // display the array list
  System.out.println("Contents of al: " + al);
  // Remove elements from the array list
  al.remove("F");
  al.remove(2);
  System.out.println("Size of al after deletions: " + al.size());
  System.out.println("Contents of al: " + al);
  }
  }

Example taken from http://www.tutorialspoint.com/java/java_arraylist_class.htm

Upvotes: 0

bakoyaro
bakoyaro

Reputation: 2558

Use ArrayList instead of a primitive array, then when you have all of the values in the ArrayList (which will grow) you can convert it to a primitive array like so:

 List<Character> l = new ArrayList<Character>();
 ...
 l.toArray();

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201467

Switch to the collection (like your mentioned ArrayList), because it will be significantly more efficient then creating a new array and copying the values for every insert (which you must do if you use an array because, as you noted, arrays are statically sized at creation).

The ArrayList Javadoc says (in part),

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Upvotes: 5

Related Questions