How to fill out array properties of the object with multiple values - java

I do use strust-json library for converting java object to json automatically. The task is to provide the following output from the server to client:
{
"results":
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
}
I've created object with array properties:
public class ResultsOrganisationUnit {
private Integer[] id = new Integer[100];
private String[] text = new String[100];
public Integer[] getId() {
return id;
}
public void setId(Integer[] id) {
this.id = id;
}
public String[] getText() {
return text;
}
public void setText(String[] text) {
this.text = text;
}
}
Initialized it:
results = new ResultsOrganisationUnit();
and then later I tried to fill it out using for-each cycle:
for (OrganisationUnitNameHistory children : children2){
results.setId(new Integer[] {children.getOrganisationunitCode()});
results.setText(new String[] {children.getName()});
}
The thing is, I only get the last value of array in the output from client side.
{"results":{"id":[3509],"text":["text 1"]}}
However, the object children for example has all 5 values. It seems like I'm overriding the same array value each time, instead of filling out the new one. I'm confused where is that logical error, which I'm making. It must be something simple..

You should wrap id and text into new class, and store collection of them inside result:
public class OrganisationUnit {
private Integer id;
private String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
public class Results {
private List<OrganisationUnit> results = new ArrayList<>();
public List<OrganisationUnit> getResults() {
return results;
}
public void setResults(List<OrganisationUnit> results) {
this.results = results;
}
}
Fill it using loop:
Results results = new Results();
for (OrganisationUnitNameHistory children : children2) {
OrganisationUnit ou = new OrganisationUnit();
ou.setId(children.getOrganisationunitCode());
ou.setText(children.getName());
results.getResults().add(ou);
}
Or directly without using Result class:
List<OrganisationUnit> results = new ArrayList<>();
for (OrganisationUnitNameHistory children : children2) {
OrganisationUnit ou = new OrganisationUnit();
ou.setId(children.getOrganisationunitCode());
ou.setText(children.getName());
results.add(ou);
}

You are getting the last value, because that is what you ask your code to do.
I am not sure what kind of variabel the children2 is, but lets say its a List<ResultsOrganisationUnit> then one solution would be to:
private Integer[] ids = new Integer[100];
private String[] texts = new String[100];
for ( int i=0; i < children2.size(); i++) {
ids[i] = children2[i].getOrganisationunitCode();
texts[i] = children2[i].getName();
}
results.setId(ids);
results.setText(texts);
But still the task as you are referring to is not accomplished by your code.
What you will be looking at is something similar to the following, depending on the values you provide:
{
"results":
{
"id":[1, 2, 3],
"text":["text 1", "text 2", "text 3"]
}
}
To be able to get what you are asking for in the comment is to create your OrganisationUnit like this:
public class OrganisationUnit{
private Integer id;
private String text;
public Integer getId(){return id;}
public void setId(Integer id){this.id = id;}
public String getText(){return text;}
public void setText(String text){this.text = text;}
}
And then store the values for the results in a List<OrganisationUnit>
List<OrganisationUnit> results = new ArrayList();
for (OrganisationUnitNameHistory child : children2) {
OrganisationUnit tempChild = new OrganisationUnit();
tempChild.setId(child.getOrganisationunitCode());
tempChild.setText(child.getName());
results.add(tempChild);
}
The results that you return should be according what you are looking for in the comment field.

The structure of your json does not follow the pattern, since results, so you left it look like, should be an array.
See that https://www.json.org/.
What could be done would be the following structure:
{
results:
    [
{"id": 1, "text": "Option 1"},
{"id": 2, "text": "Option 2"}
]
}
You need to put in your array a value, however you are always updating your references to a new array:
...
private Integer[] id = new Integer [100];
...
public void setId(Integer[] id){
    // here you are adding the reference to a new array, overwriting your id reference to which you started with a new Integer[100]
    this.id = id;
}
In order for the array to store the ids you may need a new property to store the current position. And your setId should get a reference to an Integer instead of an Integers Array, and add to this array the value.
private Integer[] id = new Integer[100];
private int nextPosition = 0;
...
// I omit the treatment here so that it does not add a position beyond what its array allows for simplification purposes.
public void setId(Integer[] id) {
    this.id[nextPosition] = id;
    nextPosition = nextPosition + 1;
}
...
So you would persist more values, but from what I understood is not exactly what you need, since the structure of the outcome would continue to be the same for which you are complaining:
// No association between ids and texts
{
"results":
{
"id": [3509, 8987, 1234, 777, 987],
"text": ["text 1", "text 2", "text 3"]
}
}
Note that results is an array of a complex object, not a Value Object such as String and Integer. Perhaps the ideal would be you to create a new object to behave and associate the id and text properties.
public class ResultsOrganisationChild {
   private Integer id;
   private String text;
   public ResultsOrganisationChild(Integer id, String text){
this.id = id;
        this.text = text;
   }
   // add some gets and sets
}
Optionally, you could use a List instead of an array, because then you will not have to worry about your object growing beyond what you might have initially foreseen, besides not having to worry about the next position:
public class ResultsOrganisationUnit {
    private List<ResultsOrganisationChild> list = new ArrayList<>();
    
    public void addChild(ResultsOrganisationChild child) {
        list.add(child);
    }
    public List<ResultsOrganisationChild> getChild() {
        return this.list;
    }
}
Your for-each would look like this:
ResultsOrganisationUnit results = new ResultsOrganisationUnit();
for(OrganizationUnitNameHistory children: children2) {
    
    ResultsOrganisationChild child = new ResultsOrganisationChild (children.getOrganisationunitCode(), children.getName());
    results.addChild(child);
}

Related

What is the best way to get the result through Java8 function?

I need to filter elements and then sort based on certain column. Post that I would need to find the unique entries based on combination of columns. Since it is file processing, pipe(|) is used as delimiter to denote the column value.
String s1= "12|Thor|Asgaurd|1000000|Avenger|Active"
String s2= "234|Iron man|New York|9999999|Avenger|Active"
String s3= "420|Loki|Asgaurd|||Inactive"
String s4= "12|Thor|Asgaurd Bank|1000000|Avenger HQ|Active"
Data first needs to be filtered based on the Active/Inactive status. Then it needs to be sorted based on 4th column. Lastly, the uniqueness needs to be maintained by combining column 1,2,3.
Expected Output =
"234|Iron man|New York|9999999|Avenger|Active"
"12|Thor|Asgaurd|1000000|Avenger|Active"
Creating a model class and parsing the string is the way to go, but if for some reaseon you don't want to do that you can do it this way:
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
List<String> result = Stream.of(s1, s2, s3, s4)
.filter(s -> s.split("\\|")[5].equals("Active"))
.sorted(Comparator.comparing(e -> e.split("\\|")[4]))
.collect(Collectors.toList());
First of all you should create an Object which represents your String data. Something like this:
public class MyObject {
private int id;
private String name;
private String location;
private Integer value;
private String category;
private String state;
public MyObject(String entry) {
String[] parts = entry.split("\\|");
if (parts.length != 6) {
throw new IllegalArgumentException("entry has not 6 parts");
}
id = Integer.parseInt(parts[0]);
name = parts[1];
location = parts[2];
try {
value = Integer.parseInt(parts[3]);
} catch (NumberFormatException ignored) {
}
category = parts[4];
state = parts[5];
}
// getters
#Override
public String toString() {
return String.join("|", String.valueOf(id), name, location, String.valueOf(value), category, state);
}
}
With this you can create a Stream of objects from your Strings and to the filter, sort and distinct operations afterwards:
Collection<MyObject> result = Stream.of(s1, s2, s3, s4)
.map(MyObject::new)
.filter(o -> "Active".equals(o.getState()))
.sorted(Comparator.comparing(MyObject::getValue).reversed())
.collect(Collectors.toMap(o -> Arrays.asList(o.getId(), o.getName()),
Function.identity(), (o1, o2) -> o1, LinkedHashMap::new))
.values();
result.forEach(System.out::println);
After the map operation you filter the values by state and sort them by column 4 (value in my case). At the end you collect all the values in a map for the distinct operation. Add all values you need distinction for to the Arrays.asList(). As values the map takes all the original values (Function.identity()). For duplicates we keep the first value ((o1, o2) -> o1) and we are using a LinkedHashMap to keep the order of the items. At the end wee use only the values of the map.
If you need a List instead of a Collection use new ArrayList(result).
The result will be this:
234|Iron man|New York|9999999|Avenger|Active
12|Thor|Asgaurd|1000000|Avenger|Active
It seems like you're unable to filter while everything is string only.
Try this,
create a new model class which can hold your columns.
Ex:
class MyData{
private String name;
private String city;
private String distance;
private String organization;
private String status;
//And create Getter Setter method for all above fields.
}
Now came to your main class where you can play with your code stuff.
Map<MyData> map = new HashMap<MyData>();
MyData myData = new MyData();
myData.setName("Thor");
myData.setCity("Asgaurd");
myData.setDistance("1000000");
myData.setOrganization("Avenger");
myData.setStatus("Active");
map.put(12, myData);
//Same thing for all other data (note: use the loop for data insertion in map)
Map<String, MyData> sorted = map.entrySet().stream().sorted(comparingByValue()).collect(toMap(e -> e.getKey(), e -> e.getValue().getName(), (e1, e2) -> e2,LinkedHashMap::new));
System.out.println("map after sorting by values: " + sorted);
You can solve your task this way:
Firstly, just create POJO(Plain Old Java Object) and override the toString() method.
class MarvelPerson {
private Integer id;
private String name;
private String origin;
private Integer point = null;
private String faction;
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public Integer getPoint() {
return point;
}
public void setPoint(Integer point) {
this.point = point;
}
public String getFaction() {
return faction;
}
public void setFaction(String faction) {
this.faction = faction;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(id);
builder.append("|");
builder.append(name);
builder.append("|");
builder.append(origin);
builder.append("|");
if(point != null) {
builder.append(point);
}
builder.append("|");
if(faction != null) {
builder.append(faction);
}
builder.append("|");
builder.append(status);
return builder.toString();
}
}
Then, you should write the parser from string to MarvelPerson. Side note: Carefully, my implementation is pretty basic, and I suppose it should be modified because I may not have foreseen some corner cases.
class PersonParser {
static MarvelPerson parse(String data) {
MarvelPerson person = new MarvelPerson();
String[] array = data.split("\\|", -1);
person.setId(Integer.parseInt(array[0]));
person.setName(array[1]);
person.setOrigin(array[2]);
if(!array[3].isEmpty()) {
person.setPoint(Integer.parseInt(array[3]));
}
if(!array[4].isEmpty()) {
person.setFaction(array[4]);
}
person.setStatus(array[5]);
return person;
}
}
And then your solution:
public class Test {
public static void main(String[] args) {
List<MarvelPerson> list = new ArrayList<>();
list.add(PersonParser.parse("12|Thor|Asgaurd|1000000|Avenger|Active"));
list.add(PersonParser.parse("234|Iron man|New York|9999999|Avenger|Active"));
list.add(PersonParser.parse("420|Loki|Asgaurd|||Inactive"));
list.add(PersonParser.parse("12|Thor|Asgaurd Bank|1000000|Avenger HQ|Actie"));
list.stream()
.filter(marvelPerson -> marvelPerson.getStatus().equals("Active"))
.sorted((o1, o2) -> o1.getPoint() <= o2.getPoint() ? 1 : -1)
.forEach(marvelPerson -> {
System.out.println(marvelPerson.toString());
});
}
}
The output to be printed:
234|Iron man|New York|9999999|Avenger|Active
12|Thor|Asgaurd|1000000|Avenger|Active

How to collect properties of List<Map> by unique property using MultiMap?

I have List of stories. Using unique property(id) I want to collect keyword and targeting as list of values. Can I do this with MultiMap? Or is there other library for this?
[{
id = 1,
title = Onboarding,
keyword = new joinee,
targeting = finance
}, {
id = 1,
title = Onboarding,
keyword = training,
targeting = HR
}]
The Desired output must like this :
{
id = 1,
title = Onboarding,
keyword = [new joinee,training], //may be keywords - plural
targeting = [HR,finance]
}
Sample my tried Code as follows:
package prac;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JavaPrac {
public static void main(String[] args) {
Multimap<Integer, Map> multiMap = ArrayListMultimap.create();
List<Map> stories=new ArrayList();
Map story1=new HashMap();
story1.put("id", 1);
story1.put("title", "Onboarding");
story1.put("keyword","new joinee");
story1.put("targeting","finance");
Map story2=new HashMap();
story2.put("id", 1);
story2.put("title", "Onboarding");
story2.put("keyword","training");
story2.put("targeting","HR");
stories.add(story1);
stories.add(story2);
System.out.println(stories);
stories.forEach((story) -> {
multiMap.put((Integer) story.get("id"), story);
});
}
}
A multimap can only store multiple values per key but what you want is to combine those multiple values so that you get one element that has the same id and title as well as a collection of keywords and targeting information. Thus it would probably be best to either have something like MultiStory or already have Story contain those collections.
I'd suggest using proper objects instead of just maps but with maps and Java 8 lambdas you could use compute() etc. to build maps that contain collections and combine maps that don't.
Here's an example of how you'd do it with maps. Note that this is very bad style and an example using proper pojos will follow:
Disclaimer: example based on the OP's code, not recommended (read text above)
//Problem 1: we don't know the type of the values, i.e. we could put anything for "id" etc.
Map<String, Object> story1=new HashMap<>();
story1.put("id", 1);
story1.put("title", "Onboarding");
story1.put("keyword","new joinee");
story1.put("targeting","finance");
Map<String, Object> story2=new HashMap<>();
story2.put("id", 1);
story2.put("title", "Onboarding");
story2.put("keyword","training");
story2.put("targeting","HR");
List<Map<String, Object>> stories=new ArrayList<>();
stories.add(story1);
stories.add(story2);
Map<Integer, Map<String, Object>> combined = new HashMap<>();
stories.forEach((story) -> {
//Problem 2: because we don't know the type of the values we need a lot of nasty casts
Map<String, Object> combinedStory = combined.computeIfAbsent( (Integer)story.get( "id" ), k -> new HashMap<String, Object>() );
combinedStory.put("id", story.get( "id" ) );
combinedStory.put("title", story.get( "title" ) );
//Problem 3: the combined map would look a lot like your "story" maps but would contain different types
((List<String>)combinedStory.computeIfAbsent( "keyword", v -> new List<String>() )).add( (String)story.get("keyword") );
((List<String>)combinedStory.computeIfAbsent( "targeting", v -> new List<String>() )).add( (String)story.get("targeting") );
});
Using POJOs
Here's a greatly simplified example of how you'd do it with proper Java objects (POJOs). Note that those are meant to resemble your code as much as possible and there are a lot of other issues but addressing those would be way too much here and better designed code would be a lot larger and probably harder to understand - after all it's just meant to show you a difference.
First let's define our classes (for simplicity I made the fields public, you'd normally not do that):
class Story {
public final int id;
public String title;
public String keyword;
public String targeting;
public Story(int storyId) {
id = storyId ;
}
}
class MultiStory {
public final int id;
public String title;
public Set<String> keywords = new HashSet<>();
public Set<String> targetingInfo = new HashSet<>();
public MultiStory( int storyId ) {
id = storyId ;
}
}
Then let's reiterate the code above:
Story story1=new Story( 1 );
story1.title = "Onboarding";
story1.keyword = "new joinee";
story1.targeting = "finance";
Story story2=new Story( 1 );
story2.title = "Onboarding";
story2.keyword = "training";
story2.targeting = "HR";
List<Story> stories=new ArrayList<>();
stories.add(story1);
stories.add(story2);
Map<Integer, MultiStory> combined = new HashMap<>();
stories.forEach((story) -> {
MultiStory multiStory = combined.computeIfAbsent( story.id, v -> new MultiStory( story.id ) );
multiStory.title = story.title;
multiStory.keywords.add( story.keyword );
multiStory.targetingInfo.add( story.targeting );
});
As you can see, there are no casts needed and it's clear what fields are available (though not necessarily filled) which makes it easier to reason about the code and spot errors (the compiler can help a lot here which it couldn't to in the example that uses maps).
Here is a solution using classes to represent the story and tags:
public static void main(String[] args) {
TagsCollector app = new TagsCollector();
app.go();
}
private void go() {
List<Story> stories = createStories();
System.out.println(stories);
Map<Long, Tags> tagsById = collectTags(stories);
tagsById.forEach((aLong, tags) -> System.out.println(tags));
}
private List<Story> createStories() {
return Arrays.asList(
new Story(1, "Onboarding", "new joinee", "finance"),
new Story(1, "Onboarding", "training", "HR")
);
}
private Map<Long, Tags> collectTags(List<Story> stories) {
Map<Long, Tags> tagsById = new HashMap<>();
stories.forEach(s -> {
Tags tags = tagsById.computeIfAbsent(s.id, v -> new Tags(s));
tags.getKeywords().add(s.getKeyword());
tags.getTargetings().add(s.getTargeting());
});
return tagsById;
}
Class used to represent the Story:
public class Story {
private final long id;
private final String title;
private final String keyword;
private final String targeting;
public Story(long id, String title, String keyword, String targeting) {
this.id = id;
this.title = title;
this.keyword = keyword;
this.targeting = targeting;
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getKeyword() {
return keyword;
}
public String getTargeting() {
return targeting;
}
#Override
public String toString() {
return String.format("Story %s, title=%s, keyword=%s, targeting=%s", id, title, keyword, targeting);
}
}
Class used to represent the Tags:
public class Tags {
private final long id;
private final String title;
private final List<String> keywords = new ArrayList<>();
private final List<String> targetings = new ArrayList<>();
Tags(Story story) {
this.id = story.id;
this.title = story.title;
}
public List<String> getKeywords() {
return keywords;
}
public List<String> getTargetings() {
return targetings;
}
#Override
public String toString() {
return String.format("Tags for id %s, title:%s: keywords=%s, targetings=%s", id, title, keywords, targetings);
}
}
Output
[Story 1, title=Onboarding, keyword=new joinee, targeting=finance, Story 1, title=Onboarding, keyword=training, targeting=HR]
Tags for id 1, title:Onboarding: keywords=[new joinee, training], targetings=[finance, HR]
Yes, you can do that with a Multimap. First I would define a pojo for Story in order to make things clearer:
public class Story {
private int id;
private String title;
private String keyword;
private String targeting;
//getters setters
}
Second you need to define a key with hashcode and equals.
public static class StoryKey {
private final int id;
private final String title;
public StoryKey(int id, String title) {
this.id = id;
this.title = title;
}
//getters
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StoryKey storyKey = (StoryKey) o;
if (id != storyKey.id) return false;
return title != null ? title.equals(storyKey.title) : storyKey.title == null;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (title != null ? title.hashCode() : 0);
return result;
}
The code will look like:
ArrayListMultimap<StoryKey, Story> multiMap = ArrayListMultimap.create();
List<Story> stories = new ArrayList();
Story story1 = new Story();
story1.setId(1);
story1.setTitle("Onboarding");
story1.setKeyword("training");
story1.setTargeting("HR");
Story story2 = new Story();
story2.setId(1);
story2.setTitle("Onboarding");
story2.setKeyword("new joinee,");
story2.setTargeting("finance");
stories.add(story1);
stories.add(story2);
System.out.println(stories);
stories.
forEach((story) -> {
multiMap.put(new StoryKey(story.getId(), story.getTitle()), story);
});
multiMap.keys().forEach(key ->
System.out.println(
"id =" + key.getId() +
" title =" + key.getTitle()+
"keyword =" + multiMap.get(key).stream().map(story->story.getKeyword()).collect(Collectors.toList()).toString()+
"targeting ="+ multiMap.get(key).stream().map(story->story.getTargeting()).collect(Collectors.toList()).toString())
);

Process array list from map

We are trying to access the array of object that placed inside a map.
Can any one guide us to get length of the array as well as fetching each element from the list. Sample map object given bellow.
{
storeId = 1,
ShipToStreetLine1 = test 123,
ShipToCity = Seattle,
OrderDetails = [{
distributor_name = SS,
product_name = HORN 80897 AM GUN 300BO 125 HP 50/10
}]
}
We need to get the size of orderDetails array and if data present, then I want to fetch product_name.
You can try this:
Create a POJO which is type of what you are getting in orderDetails
Like
public class OrderDetailElement{
private String distributor_name;
private String product_name;
public String getDistributor_name() {
return distributor_name;
}
public void setDistributor_name(String distributor_name) {
this.distributor_name = distributor_name;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
}
in your logic class you can do is
ArrayList<OrderDetailElement> orderDetails = yourMap.get("OrderDetails");
List<String> products = new ArrayList<String>();
if (orderDetails.size() > 0) {
for (OrderDetailElement orderDetailElement : orderDetails) {
products.add(orderDetailElement.getProduct_name());
}
}

How to change the value of variable based on the available values in List

I need your help in changing the value of a boolean variable based on the available values in a List. I defined a class called Student:
public class Student {
private Integer id;//Getter and Setter
private String name;//Getter and Setter
private String location;//Getter and Setter
private String remarks;//Getter and Setter
private boolean disable;//Getter and Setter
public Student(Integer id, String name, String location, String remarks, boolean disable){
this.id = id;
this.name = name;
this.location = location;
this.remarks=remarks;
this.disable=disable;
}
By default in the bean, the value of the disable is true. In the program, I have two lists which are employeeList and selectedEmployees. The employeeList has the values and the selectedEmployees List has the selected values:
private List<Student> employeeList = new ArrayList<Student>();
private List<Student> selectedEmployees;
private boolean disable;
#PostConstruct
public void init() {
//add Employees
disable=true;
Student w1 = new Student(111, "AAAA", "ZZZZ", "", disable);
Student w2 = new Student(222, "CCCCC", "ZZZZZ", "OUT", disable);
Student w3 = new Student(333, "BBBBBB", "YYYYYYY", "IN", disable);
employeeList.add(w1);
employeeList.add(w2);
employeeList.add(w3);
}
However, I am having a method which is called EnableInputText that will be called to check if any of the above values is in the selectedEmployees List, then it should change the value of the disable variable to false:
public void EnableInputText(SelectEvent event) {
for(int i=0;i<=selectedEmployees.size();i++){
for(int j=0;j<=employeeList.size();j++){
if(selectedEmployees.get(i).getId().equals(employeeList.get(j).getId()))
{
selectedEmployees.get(j).setDisable(false);
break;
}
}
}
}
But with the above code, I am getting the error:
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 at
java.util.ArrayList.RangeCheck(ArrayList.java:547) at
java.util.ArrayList.get(ArrayList.java:322)
selectedEmployees.get(j).setDisable(false);
i think you meant to use i instead of j for that line?
or on the flip side probably:
employeeList.get(j).setDisable(false);

Adding items to ArrayList in a loop

So i'm trying to add items (which have to be static) to an ArrayList using this class template:
AllEventInformationStatic.java:
public class AllEventInformationStatic {
public static int id;
public static String name;
public static String type;
public static String date;
public static String desc;
public static String location;
public AllEventInformationStatic(int id, String name, String type, String date, String desc, String location)
{
AllEventInformationStatic.id = id;
AllEventInformationStatic.name = name;
AllEventInformationStatic.type = type;
AllEventInformationStatic.date = date;
AllEventInformationStatic.desc = desc;
AllEventInformationStatic.location = location;
}
}
AllEventResponseStatic.java:
public class AllEventResponseStatic {
public static ArrayList<AllEventInformationStatic> events;
}
And here is the iteration to fill the ArrayList:
AllEventResponseStatic.events = new ArrayList<AllEventInformationStatic>();
for (int i = 0; i < allEventResponse.events.size(); i++)
{
AllEventResponseStatic.events.
add(new AllEventInformationStatic(42, "bowling",
"event", "11/12/2015",
"enjoy it", "paris"));
String name = AllEventResponseStatic.events.get(0).name;
}
String name_bis = AllEventResponseStatic.events.get(0).name;
So the variable name display "bowling" but name_bis is Null.
it seems like it just clear the whole arraylist after the iteration and I have don't know why..
If you have any idea where the problem is?
Assuming you mean allEventResponseStatic in loop condition and not allEventResponse.
AllEventResponseStatic.events = new ArrayList<AllEventInformationStatic>();
After this call the size of list is zero so loop is never called. Hence you get null on index 0 after the loop
for (int i = 0; i < allEventResponseStatic.events.size(); i++)
{
AllEventResponseStatic.events.
add(new AllEventInformationStatic(42, "bowling",
"event", "11/12/2015",
"enjoy it", "paris"));
String name = AllEventResponseStatic.events.get(0).name;
}
Also, please research what static keyword does, as it is useless here and causes far bigger problems in your code.

Categories