Skip to content Skip to sidebar Skip to footer

Continuously Changing Array Size

I have an array of strings but the values in array is changing continuously. Is there any other way of managing the array except removing items and changing index locations? pu

Solution 1:

Use ArrayList in place of String[] .. And you can also easily cast ArrayList to String[] for your final output as

ArrayList<String>  mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);

Solution 2:

You could use a List. It changes size depending on how many objects you put in it.

List<String> list = new ArrayList<String>;
public static void main(String[] args) {
     list.add("string 1"); //Add strings to the list
     list.add("string 2");
     System.out.println(list.get(0)); //Get the values from the list
     System.out.println(list.get(1));
}

Solution 3:

Instead of using Arrays, you could use ArrayLists. You can add as much as you want to them without having to re-size the array and once you no longer need an item it can be removed. Here is a link to an overview of ArrayLists and some examples using them: http://www.tutorialspoint.com/java/java_arraylist_class.htm

Hope this helps.


Solution 4:

If you know the max count of devices. Then you can define an array with max size.

String[]  deviceId = new String[MAX_DEVICE_COUNT];

Or else simply go with a List.

List<String>  deviceId=new ArrayList<String>();

Don't worry about performance, so much with a array.


Solution 5:

- In Java arrays are initialized at the time of its creation whether its declared at class level or at local level.

- Once the size is defined of an array in Java it can't be changed.

- Its better to use Collection like List.

- It has the flexibility to add and delete the items in it, and one can also at items at desired location in the List.

- List is an Interface in Java, you can use its concrete sub classes like ArrayList, LinkedList..etc.


Post a Comment for "Continuously Changing Array Size"