Android String Initialisation - java

I have a query about strings.
I'm declaring my string array as:
private static String[] name;
I'm then trying to add a string to it:
name[0] = temp // Where temp as another string
I am getting a nullpointer error with the above code. Am I initialising my string array correctly?

Looks like you've missed to write
name = new String[CAPACITY];
somewhere

If you want to add dynamically elements to an Array of Strings I would recommend you to do
private static ArrayList<String> name = new ArrayList<String>();
and then use below to add Strings:
name.add(temp);
If you know the size that it will have, then you can create an array like this:
private static String[] name = new String[10]; //if it's going to have 10 elements (typo corrected)

The problem is you have not initialized your string array.
You can declare and initialize it this way:
private static String[] name = new String[4]; Where '4' is the size of your array.
or:
private static String[] name = {temp, temp2, temp3}; Where the temps are each individual item in the array.

At the point
private static String[] name;
in your code, 'name' is still null.
for an array of Strings you have to declare the (constant) number of strings you want to store.
int n = 10;
private static String[] name = new String[n];
You then cannot ever write more than n strings to your array.
If you want to have the number of strings dynamically, you have to use a Vector<String> or an ArrayList<String>. Both objects use the myStrings.add(String string)-method to add a string and you can access strings by calling myStrings.get(int position).

Related

Can the Length of String array be changed in JAVA ?

I thought that the String array length cannot be changed once we define the size.
But I am not sure why it is allowing me to change it here (for the piece of code)?
public class Test1 {
public static void main(String[] args) {
//size =3
String[] roleNameArray = { "a", "b", "c" };
// I also tried with
//String[] roleNameArray = new String[3];
//roleNameArray[0]="a";
//roleNameArray[1]="b";
//roleNameArray[2]="c";
System.out.println(roleNameArray.length);
roleNameArray = addMoreValues();
// size changed to 4
System.out.println(roleNameArray.length);
}
public static String[] addMoreValues() {
final String[] roleNameArra = new String[4];
roleNameArra[0] = "a";
roleNameArra[1] = "b";
roleNameArra[2] = "c";
roleNameArra[3] = "d";
return roleNameArra;
}
}
OUTPUT:- 3 4
Here the size=3 when we initialized the array "roleNameArray"
Then the size changes to 4 for "roleNameArra" being equated to "roleNameArray".
Questions:-
The size of String array has been changed in this case?
If not what happens in memory in this case of JAVA? (java
version used 1.8)
In the method addMoreValues you are creating a new array, which has nothing to do with the old array. Only because you fill the variable named roleNameArray with a reference to the new array you see the updated length. If you just call addMoreValues without updating the local variable (so without roleNameArray =), the old and unchanged array will be used.
That's because you created new array instance.
final String[] roleNameArra = new String[4];
And then you changed reference of old array to the new one (returned from function).
Maybe this ?
final String[] roleNameArra = new String[4];
You are not changing its size you are assigning it to a new one.
I recommend that you read more about java collections.
You haven't changed the length of the roleNameArray. In your method you created new array of size 4 and then returned the reference to it.
So now in roleNameArray you have array from your method, not from main.

Add String Arrays in ArrayList

I have an ArrayList defined as:
ArrayList<String[]> params=new ArrayList<String[]>();
It contains parameters ("name", value) in String Arrays. I would like to insert elements in the ArrayList:
params.add({"param1", param1});
But when I try that I get an error.
What is the simplest way to add String Arrays in ArrayList. Do I have to declare a new array each time?
A declaration is the only time you can just use braces, e.g.
String[] test = {"param1", param1};
In all other times, you must use new String[] also.
params.add(new String[] {"param1", param1});
Make a string with some special sequence. Add it in ArrayList and then split it when you need it. For example:
ArrayList<String> str_list = new ArrayList<String>();
String str = "name&&&value";
// Add str to str_list
str_list.add(str);
Then fetch it from arraylist and split it using following code:
String str1 = str_list.get(index);
String[] values = str1.split("&&&");
values[0] will be name and values[1] will be value.
You should read up on ArrayLists here
But after initialization you can do this:
params.add("String");
params.add(aStringObject);
Your initialization is incorrect as well; If you want a ArrayList of Strings it should be:
ArrayList<String> params = new ArrayList<String>();

how to store a array of String in Array List. can we use array of an Array List. if yes then how?

is it possible to run the following code with logic in 6th line ?
public class arraylist{
public static void main(String args{}){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible?
}
Iterator it=al1.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
Change al.add(s); by al.addAll(Arrays.asList(s)); and you should be all set.
Try the following:
ArrayList<String> al = new ArrayList<String>(Arrays.asList(s));
You have the answer in your question.
When you say you want to convert array asList
As many have already suggested, use Arrays.asList. But before the code would work, you would still need to fix the formatting as you have code outside the main method that is referring to your array list variable in the main method.
public static void main(String[] args){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(Arrays.asList(s));
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible ?
Yes. It is possible.You can add any object to ArrayList including array object.
But while iterating the ArrayList object you will get an array element by calling it.next().So output will be String representation of array object not the array elements
So try this
String s[]={"Sam","Tom","Jerry"};
ArrayList<String> al=Arrays.asList(s);
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
I did the following to store arrays in a ArrayList. The declaration is:
ArrayList<String[]> training = new ArrayList<String[]>();
To input the words and add it:
String input = sc.nextLine();
s1 = input.split(" ");
training.add(s1);
The split method splits the string with spaces and stores each word in the respective index in array s1 which was already declared with the size required for the program."sc" is the scanner object already declared.The individual arrays can be accessed by using:
String s4[] = training.get(index_of_array_you_want);
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList arr=new ArrayList(Arrays.asList(array))

how can i merg a String array and boolean array

i have two array like this
String[][] name=new String[4][10];
boolean[] accun=new boolean[10];
name[0][0]="ali";
name[0][1]="max";
name[0][2]="ahmad";
etc.....
name[1][0]="9999";
name[1][1]="9999";
name[1][2]="9999";
etc...
and name[2][..] ,name[3][..] like that.
now how can i merge this two array together?like this.
name [5][0]=true;
name [0][0]="alex";
Thanks for your any Help.
The type of an array is the same for all elements of an array. The only way this would work for you is to use Object[][] because Object is a supertype of both String and Boolean. However, what you should probably be doing is creating a class which has members which are currently being represented by the different indices of your array. For example:
class Foo {
String name;
int count;
boolean isFoo;
}
Foo[] foos = new Foo[10];
foo[0] = new Foo();
foo[0].name = "aaaa";
foo[0].count = 9999;
foo[0].isFoo = true;
You should then also look into constructors and accessor methods to make the code more idiomatic Java.
Your question is bit ambiguous.My assumption is you are trying to ask how to different type of objects in array. Here you should go
Object[][] name = new Object[4][10];
Now you can store both int and string objects under name array.

Referring a variable with a variable in java

I have got into a strange strange situation. I have 3 sets of strings like this
String set1q1="something"; //associated with randomNum=1
String set1q2="something";
String set1q3="something";
String set1q4="something";
... and so on
String set2q1="something"; //randomNum=2
String set2q2="something";
String set2q3="something";
String set2q4="something";
... and so on
String set3q1="something"; //randomNum=3
String set3q2="something";
String set3q3="something";
String set3q4="something";
... and so on
All these strings are initialised only once. Now in my program i generate a random number between 1-3. I converted this random number into a string and stored it into a string called set.
String set=randomNum.toString();
Now next intead of using "if-else" to send the data(if randomnum=1 send set1q1-5, if randomnum=2 then send set2q1-5), I want the appropriate data to be sent using one line.
For example: if random no 2 is chosen then set2q1 has to be sent where the "2" in between is has to be the value of "set"(which is defined above).
set"set"q1 //where set can be 1,2,3
Is there any way to do this?
What you are asking for is not possible;1 it's just not the way Java works. Why don't you just use an array, or a collection?
List<List<String>> allTheStrings = new ArrayList<List<String>>();
List<String> myStrings = null;
// Add a subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
// Add another subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
...
// Obtain one of the strings
String str = allTheStrings.get(1).get(2);
1. Except in the case where these variables are members of a class, in which case you could use reflection. But really, don't.
It is not possible. Local variable identifiers are converted to numbers (stack offsets) during compilation. But you should use arrays or collections anyway
Sounds like you want to index Strings by two indices. You should use a two-dimensional String array: String[][] strings. You may then access the desired string with strings[n][m]
Or you can achieve the same effect with a List<List<String>> strings if you need the dimensions of your 2D array to grow dynamically. You'd access the value you need with strings.get(n).get(m)
If you really want to access your strings by a composed name such as set2q1, then you just need a Map<String, String> strings. Then you'd access each value with strings.get("set" + m + "q" + n)
looks to me you should look into arrays, like this:
String[] strings = new String[]{"xxx", "yyy", "zzz"};
String string = strings[randomNumber];
create an arraylist instead and reference using the list index

Categories

Resources