-5

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?

   public String[] deviceId=null; 
   deviceId=new String[deviceCount];

in my case deviceCount is changes as new device comes. so i continuously need to change array size and add or remove items

3
  • Is it a requirement that you have to use arrays. If not use dynamic arrays or linked lists Commented Oct 7, 2013 at 4:37
  • i prefer to use arrayList Commented Oct 7, 2013 at 4:37
  • learn about ArrayList and other collection objects Commented Oct 7, 2013 at 4:42

6 Answers 6

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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));
}

Comments

1

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.

Comments

1

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.

Comments

0

- 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.

Comments

0

Not sure whether i got the question correctly but you can use ArrayList or LinkedList if the size is going to change dynamically.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.