I am new to JAVA and found some of its concepts very irritating and no matter how hard I try I can not find suitable explanation for this behavior...of course there are wor around for these problems but still I want to know am I missing something very simple here or JAVA is like this???
- I have a string array in one of my class A and I want it to be filled through a method of another class B...so I create an object of class B into A and call the method B.xyz and equate it to the string arra but BOOM I can't do it....java throws a nullpointer exception..........I dont know why...
.
public class B{
public void xyz() {
String[] mystrings=new String[70];
for(int i=0;i<5;i++)
mystrings[i]=value;
return mystrings;
}
}
public class A {
public void abc() {
B b=new B();
String[] StringList;
StringList=b.xyz();
System.out.println(StringList.length);
}
}
I have a similar code fragment now sadly the length of the StrinList becomes 70....if I want to print all the strings of this array I dont have any other way....remember even though the size of mystring is 70 in class B only 5 of its components are properly initialized........SO considering I am in class A and have no way to find out how many times did the for loop in B executed......how do I a开发者_C百科ccurately loop through all the elements of StringList in A.........
PS: There are workarounds to solve this problem but I wanted to know why this happens,i.e, why the length attribute doesn't change according to the components initialized??
If you only need an array of length 5 then only initialize it as that size, e.g.:
public String[] xyz(String value) {
String[] mystrings = new String[5];
for (int i = 0; i < mystrings.length; i++) {
mystrings[i] = value;
}
return mystrings;
}
If you want an array that you can expand you should consider using ArrayList
instead. E.g.:
public List<String> abc(String value) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(value);
}
return list;
}
Then you can get its size, add to it and print the elements like this:
List<String> list = abc("foo");
System.out.println(list.size());
list.add("bar");
for (String value : list) {
System.out.println(value);
}
Hope that helps.
You declared xyz as a method with return type void
in class B
. Presumably you want a signature that returns a string array, public String[] xyz()
Also you didn't declare the array correctly in B, the correct declaration is:
String[] myStrings = new String[70];
-- Dan
String[] mystrings = new String[5];
I suggest you look at using List like ArrayList as this wraps arrays to make them easier to use.
String[] mystrings[70];
This creates an array or arrays. There are two []
I suggest you try instead.
String[] mystrings = new String[5];
精彩评论