This question already has an answer here:
How to manage Continuous Changing values in an array of strings [closed]
(1 answer)
Closed 9 years ago.
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
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);
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));
}
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.
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.
- 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.
Not sure whether i got the question correctly but you can use ArrayList or LinkedList if the size is going to change dynamically.
Related
What method can I use in adding or removing an element from my array.
Is there a method for this?
Plus, one that resizes the array automatically in cases when an element is deleted to prevent the default "0" from occupying that space.
You don't have those methods for arrays but you can use ArrayList instead. Code example:
List<String> list = new ArrayList<>();
list.add("str 1");
list.add("str 2");
list.add(0,"str 3"); // Add 3 on position 0
list.remove(1); // remove item on position 1
list.remove("str 2"); // remove first occurrence of str 2
But you can't use primitive type directly as in arrays, if you want ArrayList of int then you will use Integer class which acts as wrapper for primitive type -
List<Integer> list = new ArrayList<>();
So you can't perform all the actions that you mentioned above using arrays.
You might look into using ArrayList class in java. It has in built remove libraries as well.
Check this link out - https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int)
I have an array
String[] path={abc,bcd};
I pass this array in a method:
addElement(path);
In method
void addElement(String[] path)
{
// here i got value suppose "qsd" and i want to add it after "bcd" ie 2 index of array
path[path.lenght]="qsd";
}
But this is giving me an error.
I dont want to use an ArrayList.
The biggest problem is that arrays in Java are not trivially resizable. What you wind up doing instead is actually creating a new array, and adding each of the elements to that. This will be slower than the ArrayList code, and uglier as well.
This also means that any code which points to the old array will no longer work. If you only have one instance, you could have addElement return the new array like so
String[] addElement(String old[]){
String arr[] = new String[old.length+1];
//copy all the elements in old...
arr[old.length] = "whatever";
return arr;
}
Then use
path = addElement(path);
You should use ArrayList
Otherwise you have to resize the array by allocating new memory of the size of the original array +1, copy the elements from the old one to the new one, and add in the new element.
You can't change the size of emulated array in GWT (even if javascript arrays support this stuff). You'll have always to create a new instance of array. Most common way to solve this problem is to use one of the collection classes (like java.util.ArrayList) . Example:
ArrayList<String> path = new ArrayList<String>(Arrays.asList("abc","bbc"));
path.add("qsd");
This question already has answers here:
Empty an array in Java / processing
(8 answers)
Closed 2 years ago.
I would like to remove all the elements in the String array for instance:
String example[]={"Apple","Orange","Mango","Grape","Cherry"};
Is there any simple to do it,any snippet on it will be helpful.Thanks
If example is not final then a simple reassignment would work:
example = new String[example.length];
This assumes you need the array to remain the same size. If that's not necessary then create an empty array:
example = new String[0];
If it is final then you could null out all the elements:
Arrays.fill( example, null );
See: void Arrays#fill(Object[], Object)
Consider using an ArrayList or similar collection
example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.
Reassign again. Like example = new String[(size)]
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
Just Re-Initialize the array
example = new String[size]
or If it is inside a running loop,Just Re-declare it again,
**for(int i=1;i<=100;i++)
{
String example = new String[size]
//Your code goes here``
}**
I want to put this which will be in the main method:
int numberOfElements = readFile(args[0],capacities);
the variable numberOfElements is 28.
below is just to let you see a preview of readFile looks like.
private static int readFile (String filename, String[] capacities)
Basically I want to create the string array called capacities using the variable numberOfElements as its array size:
I'm running into problems on how to do that.
If you already know the size of the array when it is created the the following works fine:
String[] capacities = new String[numberOfElements];
But if you think the size may need to change, I urge you to look into ArrayList. It allows you to add a new element at any time and has a decent search.
String[] frobs = new String[numberOfElements];
But why not use a collection?
It looks like you are trying to create an array to hold all the results of readFile, but you don't know how big it needs to be until after it already needs to be created.
What you need to do is either use a List (for example ArrayList) which doesn't need an require that you know the size when you create it. Instead these data structures grow as elements are added to them.
Or you need to write some other function which can read the data file without storing it's values anywhere (perhaps called countFile. All this function would do was count the number of entries you would need in the array in order to hold the data when you actually read and store it using readFile.
Do I misunderstand your question? It should be simply
String[] temp = new String[numberOfElements];
can anyone tell me the error in this java declaration String[][] t=new String[15][15]; this works fine and if i use String[][] t=new String[][]; because i need to declare the variable t as dynamic as i am not sure how much values i am going to store in t.
Use ArrayList (or other array object who can handle any number of objects). A java array always has a fixed length since some memory will be reserved for the array.
ArrayList creates such array as well to store the objects. Of you add more abjects as the current reserved size of the array than ArrayList will create a new bigger array (+50% if i'm correct). There are some other implementations that act a bit different (for example they create a new array 100% of the original one when the array is full. If performance is really important for you than you can look into this.
ArrayList<ArrayList<String> t = new ArrayList<ArrayList<String>();
void fill() {
ArrayList<String> t2 = new ArrayList<String>();
t2.add("somestring");
String s = "someotherstring";
t2.add(s);
t.add(t2);
}
If you don't know how big it needs to be just declare it as
String[][] t;
and once you know how big it needs to be you can do (before trying to use the array)
t = new String[15][15];
If you're never sure how big the array need to be, you'll need to use something like a List of Lists.
List<List<String>> t = new ArrayList<List<String>>;
public void add(String str, int row, int col) {
while (row >= t.size())
t.add(new ArrayList<String>());
List<String> row_list = t.get(row);
while (col >= row_list.size())
row_list.add("");
row_list.set(col, str);
}
In Java array objects are always of fixed length. Once you have allocated them you cannot change their size. An array variable can be made to point to different array objects of different size. So you can allocate:
String[][] t;
which doesn't point to an object and allocate an object later once you know the size:
int n1,n2;
// calculate n1,n2
t = new String[n1][n2];
If you need a structure where the size can change you are much better off using ArrayList, which can be dynamically resized.
Declare it as String [][]t = null;
And Reinitialize it with actual length once you get it.
t=new String[x][y];
As bemace said, just because you are declaring the variable doesn't mean you have to initialize it immediately.
As Mark said, arrays have a fixed size. Once an array is initialized(not declared, initialized) it has a fixed size.
So, there are two possibilities:
Either you will know how big the array needs to be before you need to start using it, in which case you can simply delay your initialization as suggested by bemace.
Or you won't know how big it needs to be before you start using it, in which case you need to use a dynamically sized data structure(s). Check out the Java Collections API:
tutorial
api reference
There are several good answers already, but it has now been revealed in a comment to Mark Baijens' answer that the purpose of this question is that raju need a key to multi-value mapping.
Mark followed up that comment by suggesting raju use a HashMap<String, String> hashMap = new HashMap<String, String>(); — however that only works for a single key-value pair.
What raju needs is a
Map<String, Collection<String>> t
= new HashMap<String, List<String>>();
Adding the first value for a key requires initialization of a List for that bucket, while adding additional values requires fetching the existing list and adding the new value.
Note I used Collection<String> in the declaration, so it could be a List if the order of values is important, or it could be a Set to prevent duplicate values under the same key.
This would probably be best implemented as a Class itself, perhaps
public class MultiValueMap<K, V> extends Map<K, V>
{
...
}
so the initialization of the List on the first put(key, value) and the subsequent .add(value) to the list could be hidden in the implementation.