public class MarkerList { ArrayList<String> lat=new ArrayList<>(); ArrayList<String> lng=new ArrayList<>(); ArrayList<String> name=new ArrayList<>(); ArrayList<String> type_2=new ArrayList<>();//Type_2 public void setLat(String str) { this.lat.add(str); } public void setLng(String str) { this.lng.add(str); } public void setName(String str) { this.name.add(str); } public void setType_2(String str) { this.type_2.add(str); } public String getLat(int pos) { return lat.get(pos); } public String getLng(int pos) { return lng.get(pos); } public String getName(int pos) { return name.get(pos); } public String getType_2(int pos) { return type_2.get(pos); } public int getSize(){ return name.size(); } } 

I want to not create in the whole code 10 times ArrayList. And to create once and add data there. And after that I’ll take everything I need from there.

Am I doing right at all? Or is it a trap?

  • one
    I understand that all lists of values ​​are entered simultaneously, why not create a class with these 4 fields and then make 1 static list of this class? - pavel
  • @pavel, you can take a bit more detail. I did not fully understand your idea. But the point is this. I have a lot of lists and create 5 pieces. And after from one class each list is to transmit this wildness. Therefore, I wanted to upload and transfer one file to one file. Well or static to use. - Andro

1 answer 1

Of course, you can also make static fields (add the static modifier) ​​and this will allow you to use the same collections when creating any number of instances.

But what you describe:

I want to not create in the whole code 10 times ArrayList. And to create once and add data there. And after that I’ll take everything I need from there.

can be implemented using the Singleton pattern, in this case, the simplest variant of the pattern implementation:

 public class MarkerList { public static final MarkerList INSTANCE = new MarkerList(); ArrayList<String> lat=new ArrayList<>(); ArrayList<String> lng=new ArrayList<>(); 

You can access the instance as follows:

 MarkerList myLists = MarkerList.INSTANCE; 

It is also necessary to take into account that after you replace local instances of classes with static or Singleton, you may have problems with parallel access to this collection from different streams. The easiest way to make the current implementation applicable in a multi-threaded environment is to use Collections . This can be done as follows:

 List<String> lat = Collections.synchronizedList(new ArrayList<>());