How to add new Strings to a certain array - java

I got 4 arrays in my code and everytime a user writes something into the edittext I want to store that string in one of the array, I tried to use the toCharArray method but I don't know how to define the array where the string should be put in :S
String [] array7 = {"Hey","Was Up","Yeahh"};
TextView txtV1,txtV2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layouttry);
txtV1=(TextView)findViewById(R.id.textView1);
txtV2=(TextView)findViewById(R.id.textView2);
Bundle extras = getIntent().getExtras();
String value = extras.getString("Key"); // this value I want to add to the stringarray

If you need to add new elements I would suggest replacing your arrays with ArrayLists. This will let you use the add method to insert new elements. An example of this:
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Text here");

In your code I can only see one array on Strings, so I'm not sure about what you actually need. I'll try my best though.
Your String array is hard-coded to have only three cells in it, and they are all full. If you want to put the string into any of these places, do this:
array7[0] = value; //or:
array7[1] = value; //or:
array7[1] = value;
If you want to add value to the array without deleting the existing values, you can do something like this:
//Create a new array, larger than the original.
String[] newArray7 = new String[array7.length + 1 /*1 is the minimum you are going to need, but it is better to add more. Two times the current length would be a good idea*/];
//Copy the contents of the old array into the new one.
for (int i = 0; i < array7.length; i++){
newArray7[i] = array7[i];
}
//Set the old array's name to point to the new array object.
array7 = newArray7;
You can do this in a separate method, so whenever you need to re-size your array you can use it. You should know that the classes ArrayList and Vector already implement this mechanism for you, and you can arrayList.add(string) as much as you want.

Related

Getting ArrayIndexOutofBoundException:0 while assigning value to array

When I'm trying to assign value to my array in jsp, I'm getting ArrayIndexOutOfBoundsException:0
Below is my code,
String[] imgarray = {};
int ival = 0;
// Below code in a while loop
imgarray[ival] = iname; // Value of iname is 1.jpg, 87.jpg, 114.jpg etc...
ival++;
Please let me know if i'm doing something wrong
Thanks
Arrays are not dynamically grows as like Collections. So you have to give size of the array before adding the elements to it.
String[] imgarray = new String[10];
int ival = 0;
// Below code in a while loop
imgarray[ival] = iname; // Value of iname is 1.jpg, 87.jpg, 114.jpg etc...
ival++;
This should work.
If you know in advance how many elements your array is going to hold, then you should set the size of the array at creation time, as said Ramesh, since the size of an array cannot change after creation.
If you don’t know in advance how many elements your array will have to hold, then you need another structure. I suggest an ArrayList:
List<String> list = new ArrayList<String>();
// int ival = 0 <- not needed with a List
// below code in a while loop
list.add(iname);
// ival++

For Loop doesnt add point to an array

I have the following for loop which looks through a string ArrayList of results, each item in the string is seperated by "::":
ArrayList<String> resultsArray = MyClass.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
String pointName = pointDetails[0];
String pointDescription = pointDetails[1];
String coordinates = pointDetails[2];
//Turn coordinates into geopoints
String coord[] = coords.split(",");
Integer lng= (int) (Double.valueOf(coord[0]) * 1000000);
Integer lat = (int)(Double.valueOf(coord[1])*1000000);
GeoPoint gPoint = new GeoPoint(lng,lat);
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
arrayPointName.add(pointName);
arrayPointDescription.add(pointDescription);
arrayPointCoords.add(gPoint);
}
I know I have 20 points in the initial string ArrayList and have printed out its size to check this. However, when I print out the new arraylists, such as arrayPointName, they only contain one point. Any idea on why this is?
Look at this code:
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
Those three statements - assigning new, empty ArrayList references to your variables - are being executed on every iteration of your loop.
They should come before your loop instead: you only want to initialize the variables once (creating the three lists) and then add a new item on each iteration.
As a side note, populating multiple collections like this is normally a bad idea. It's usually better to create a single type which encapsulates the related data (name, description, coordinates in this case) and then create a single collection of items of that type. That's usually a lot easier to work with.
you used coords as an ArrayList Without initiate it .Also you initiate for each iteration arrayPointName, arrayPointDescription and arrayPointCoords that's why they lost the value created in the previous iteration. they should be initiate juste one time before starting the loop
it will be easy to help you if you give us a sample of resultsArray strring.

Adding data to an ArrayList repeatedly

I am trying to add 100 (realistically more) Strings to an ArrayList. Instead of adding each String individually, how can I use something like a for loop to add them at once. The code below is an example.
ArrayList<String> strings = new ArrayList();
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
/*
More Strings created until the 100th String
.
.
.
*/
String s100 = "Kiwi";
//for loop to try add each String to List
for(int i=0; i<100; i++)
{
//Code to add each String to the arraylist
}
Can anyone identify the how I can add each String to the list?
Thanks much appreciated
Well, you could create a sophisticated strategy using reflection to fetch all variables of a given class and add them to a List; subsequently, you could loop this List and do whatever you want.
However, I do not think it would solve your problem. Indeed, you are likely to run into several pitfalls.
I would change your approach to the problem. Create a static List and add whatever you need there (or a Singleton, it depends how you want to manage this List). Once you have the list of objects you can loop it.
Cheers,
From your comments you are dealing with custom objects. Regardless of how you want to transfer data from the objects into your ArrayList, better to use a collection. The type of the collection will depend on the source of your object data. As the data is hard-coded you could use an array. Multiple variables like these
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
become
String[] fruitArray = {
"Apple",
"Banana",
"Pear"
...
};
Then to add:
for (String fruit: fruitArray) {
strings.add(fruit);
}
As already stated my comment above, a cleaner design would be to to use a single List<MyObject> to contain all objects in a DRY approach and just extract a String as needed.

Getting rid of excess while statement

Could anybody have a look at this snippet of code and and tell me if there is a way to amalgamate the two while statements into one?
public static void main(String[] args) throws IOException
{
BufferedReader fileInput;
fileInput = new BufferedReader(new FileReader("information.txt"));
int countOfClients = 0;
while (fileInput.ready())
{
fileInput.readLine();
countOfClients ++;
}
int totalClients = countOfClients ;
Client[] clientDetails = new Client[totalClients];
int clientNumber = 0;
while (fileInput.ready())
{
String currentLineOfText = fileInput.readLine();
String clientName = currentLineOfText.substring(0, 19);
String gender = currentLineOfText.substring(20,21);
char clientGender = gender.charAt(0);
int clientAge = Integer.parseInt(currentLineOfText.substring(22,24));
String clientInterests = currentLineOfText.substring(25);
clientDetails[clientNumber] = new Client(clientName, clientGender, clientAge, clientInterests);
clientNumber++;
}
The first while statement is reading all the lines in the text, so it knows how many elements in the object array it needs.
The array clientDetails of class Client[] is then created.
The second while statement populates that array.
Can I avoid using two while statements?
Note: This is for an assignment and I have to use arrays.
As they're all saying, use an ArrayList to store the items.
If memory is an issue, you can use ArrayList.toArray() to trim it down to the bare bones.
If efficiency is an issue, you probably shouldn't be reading from a file in the first palce.
You could use an ArrayList instead of an array and simply use:
list.add(new Client(...));
If you really need an array, you can always call:
Client[] array = list.toArray();
Why create an array ? Why not have one while loop that creates an ArrayList and then (if you need an array) extract the resultant array from that using ArrayList.toArray() ?
You can avoid two while loops by changing Client[] to ArrayList();
Example:
List<Client> clientDetails = new ArrayList<Client>();
int clientNumber = 0;
while (fileInput.ready())
{
String currentLineOfText = fileInput.readLine();
String clientName = currentLineOfText.substring(0, 19);
String gender = currentLineOfText.substring(20,21);
char clientGender = gender.charAt(0);
int clientAge = Integer.parseInt(currentLineOfText.substring(22,24));
String clientInterests = currentLineOfText.substring(25);
clientDetails.add( new Client(clientName, clientGender, clientAge, clientInterests));
}
Note: Hand edited, there may be syntax errors.
If you really can't use the pre-written ArrayList class, you could always effectively re-implement it (or at least the relevant bits of it) yourself.
The key technique is to take a guess at the size of the array you might need, define an array that size, and, if you find it is too small, create a bigger array and copy all the existing values from the old to the new array, before continuing in the space that is left over.
At the other end of the loop, you might be in for yet another step, and shrink the array again (by declaring a smaller array and copying values over) so you have no empty spaces left.
Or, as recommended by all the other answers, just use an ArrayList, which already does exactly this for you...

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

Categories