There is a class called PageInfo which is like this:
I assume the max size of arrays is 5.
public static class PageInfo {
String username;
PageInfo[] followings;
Post posts[];
PageInfo (String username,PageInfo[] followings,Post[] posts) {
this.username = username;
this.followings = followings;
this.posts = posts;
}
public int getPostLength () {
int cnt = 0;
for (int i = 0; i < 5; i++) {
if (posts[i] != null )
cnt++;
}
return cnt;
}
public int getFollowingLength () {
int cnt = 0;
for (int i = 0; i < 5; i++) {
if (followings[i] != null )
cnt++;
}
return cnt;
}
}
and there is a Post class like:
public static class Post {
String cation;
int id;
PageInfo[] usersLiked;
Post (String caption, int id, PageInfo[] usersLiked) {
this.cation = caption;
this.id = id;
this.usersLiked = usersLiked;
}
}
I want to declare a user with constructor like:
PageInfo[] allusers = new PageInfo[5];
allusers[0] = new PageInfo("John", "54321", new PageInfo[5], new Post[5]);
allusers[0].followings[0] = allusers[1];
allusers[0].posts[0] = new Post("John Post", 100, new PageInfo[5]);
The "getPostLength" works well.
but when "GetFollowingLength" returns me 0. why? and how to fix it?
how can i add "followings" to the allusers[x] later in the project?
It seems that "followings" hasn't been initialized yet and the're still Null. how can i properly initalize them?
I think what you're missing is that an array is initialized with null values when you do "new PageInfo[5]" or something similar. So followings is initialized as an empty array (all values null). Same with allusers. So "allusers[0].followings[0] = allusers[1];" does not do anything here. It just sets the value to null, which it already is.
I don't know what exactly you want to achieve, so I'm not sure how you could improve your code. One way could be to initialize an array like this:
Foo array = new Foo[42];
for(int i=0; i<array.length; i++
{
array[i] = new Foo();
}
Related
I got a Post class which will contain some posts of a page!
public static class Post {
String cation;
int id;
PageInfo[] usersLiked;
boolean isValid = false;
Post (String caption, int id, PageInfo[] usersLiked) {
this.cation = caption;
this.id = id;
this.usersLiked = usersLiked;
}
}
I defined an array of Posts which some of them are not actually used yet and they're made to be used later.
For example i have 2 posts but my array of posts has a size of 5.
Post[] postArray = new Post[5];
I specify used posts with "isValid".
Then how can i don't get a NullPointerException when i'm counting valid posts size?
public int getPostLength () {
int cnt = 0;
for (int i = 0; i < 5; i++) { // 5 : arraysize
if (postArray[i].isValid == true)
cnt++;
}
return cnt;
}
public int getPostLength () {
int cnt = 0;
for (int i = 0; i < postArray.length; i++) {
if (postArray[i] != null && postArray[i].isValid)
cnt++;
}
return cnt;
}
You could do it via java streams :
long cnt= Arrays.stream(postArray).filter(Objects::nonNull).filter(Post::isValid).count()
If the postArray has only two post element, then the if statement will cause a null pointer exception.
You can't call a method or access a property of a null object.
Wrap the existing if statement with a null check.
public int getPostLength () {
int cnt = 0;
for (int i = 0; i < 5; i++) {
if (postArray[I] != null) {
if (postArray[i].isValid == true)
cnt++;
}
}
return cnt;
}
I'm wornig sqllite.i have some tables and i select name for example Customer Table and Price from AnotherTable. and i received two array list .first name's array list and secods price's array list.
this is a my source
private ArrayList<GetDictioanyClassByPosition> GetPKFromTable() {
price_array.clear();
ArrayList<GetDictioanyClassByPosition> my_list = d_Helper
.getAllPriceByPosition(0);
for (int i = 0; i < my_list.size(); i++) {
String AllPrice = my_list.get(i).getDictionaryPrice();
GetDictioanyClassByPosition cnt = new GetDictioanyClassByPosition();
System.err.println(AllPrice + "AllPrice");
cnt.setDictionaryPrice(AllPrice);
price_array.add(cnt);
}
return price_array;
}
this is a method to check price's array list and this method check name's array list
public void AllInfoFromLoanAnalysis() {
name_list.clear();
ArrayList<GetAllDictionariesClass> contact_array_from_db = d_Helper
.getAllInformationFromLoanAnalysis_Table(1, 1);
Log.e("Sizee", contact_array_from_db.size() + "sizee");
for (int i = 0; i < contact_array_from_db.size(); i++) {
int DictionaryID = contact_array_from_db.get(i).getDictionaryID();
System.out.println(DictionaryID + "DictionaryID");
GetDictioanyClassByPosition object = new GetDictioanyClassByPosition();
String name = null ;
ArrayList<GetDictioanyClassByPosition> DictionaryIdList = d_Helper
.GetDictionaryIdList(DictionaryID);
System.out.println(DictionaryIdList.size() + "DictionaryIdList");
Log.e("Sizee2", DictionaryIdList.size() + "sizee2");
for (int j = 0; j < DictionaryIdList.size(); j++) {
name= DictionaryIdList.get(j).getDictionaryName();
Log.e("object", name + "object");
object.setDictionaryName(name);
name_list.add(object);
}
for (int j = 0; j < price_array.size(); j++) {
String AllPrice = price_array.get(i).getDictionaryPrice();
object.setDictionaryPrice(AllPrice);
object.setDictionaryName(name);
price_array.add(object);
}
agroproductslistview.setAdapter(agroproduct_adapter);
}
}
and i called my BaseAdapter Like this
_adapter = new LoanProductAdapter(
getApplicationContext(), R.layout.productlistadapter,
name_list);
public class GetDictioanyClassByPosition {
private String DictionaryName;
private String DictionaryPrice;
public String getDictionaryName() {
return DictionaryName;
}
public void setDictionaryName(String DictionaryName) {
this.DictionaryName = DictionaryName;
}
public String getDictionaryPrice() {
return DictionaryPrice;
}
public void setDictionaryPrice(String DictionaryPrice) {
this.DictionaryPrice = DictionaryPrice;
}
}
i can selected and show my prices and names in different array list but i want to marge both array list and would adapter in my list view
.how i can solve my problem?
if anyone knows solution please help me
thanks
Please refer below example.
public ArrayList<customObject> _historyArrayList = new ArrayList<customObject>();
public ArrayList<customObject> _completedArraylist = new ArrayList<customObject>();
For merging simply use:
_historyArrayList.addAll(_completedArraylist);
Note: Make sure your customObject are same
public class DataStorage implements java.io.Serializable {
private static final long serialVersionUID = -5597052819894601310L;
private ArrayList<ArrayList<String>> array = new ArrayList<>();
private Map<String, String[]> nameMap;
private int index = 0;
DataStorage() {
array.add(index, new ArrayList<String>());
}
public void addDataToRow() {
index += 1;
array.add(index, new ArrayList<String>());
array.get(index).add(new String());
}
public void addDataToColumn(int pos, String data) {
array.get(index).add(pos, data);
}
public int rowSize() {
return array.size();
}
public int colSize() {
return array.get(index).size();
}
public String initNameMap() {
nameMap = new TreeMap<>();
String out = "";
for(int i = 2; i < array.size(); i++) {
String[] infoHolder = new String[40];
String name = array.get(i).get(2);
int index = 0;
for(int w = 3; w < array.get(i).size(); w++) {
System.out.println(index);
infoHolder[index] = array.get(i).get(w);
index++;
}
nameMap.put(name, infoHolder);
}
for(String x : nameMap.keySet()) out += x + "\n";
return out;
}
public String navigateArray(int rStart, int cStart) {
String out = "";
for(int i = rStart; i < array.size(); i++) {
for(int w = cStart; w < array.get(i).size(); w++) {
out += array.get(i).get(w) + " ";
}
out += "\n";
}
return out;
}
}
So this is what is happening. I have the class that I have included in this question. I created and object of this class and populated the ArrayList in this class with information from a file, then I serialized the object. Later on, I added the initNameMap() method, and added a Map initialized as a TreeMap. Now, I have deserialized the object I serialized before, and I can retrieve the information in it, but when I call the initNameMap() method it gives me the following exceptions:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 1 at this segment of code:
String name = array.get(i).get(2);
and a java.lang.NullPointerException at this segment of code:
nameMap.put(name, infoHolder);
I simply do not understand why this is happening. It is extremely confusing for me, specially the indexoutofbounds exception. Could anyone explain this to me? Does it have anything to do with the serialization? Thanks
array.get(i).get(2);
The nested ArrayList in
array
has a size of 1, so when you try to get the 2nd element(which doesn't exist) you are getting the OutOfBoundsException.
name
will be null as a result. You need to figure out why the nested ArrayList in array does not have two elements as expected.
I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.
I have a set of 100 object.
How can i get a subset of 5 objects from this set ?
I'm doing this for now but it only returns me one object
int size = memberSet.size();
Set<Member> randomSet = new HashSet<Member>();
int item = new Random().nextInt(size);
int i = 0;
for(Member mbr : memberSet)
{
if (i == item){
randomSet.add(mbr);
}
i = i + 1;
}
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
Full example:
public static void main(String... args) {
Set<Member> memberSet = new HashSet<Member>();
for (int i = 0; i < 100; i++)
memberSet.add(new Member(i));
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
System.out.println(randomSet);
}
static class Member {
final int value;
public Member(int value) {
this.value = value;
}
#Override
public String toString() {
return "" + value;
}
}
Although #dacwe solution is much better I can't help myself, on joke, to just say put a for(int i=0; i<5; i++) around everything and move out the Set randomSet = new HashSet();
Outside the for loop :