There is an array in PHP:

$array = [ "status" => FALSE, "len" => 3, "msg" => "this String Hello", "data" => [0 => ["name" => "Vasya", "phone" => "123"], 1 => ["name" => "Anna", "phone" => "222"], 2 => ["name" => "John", "phone" => "300"]] ]; 

I need to create the same array in Java, how can I do this?

  • Create the most common class, three objects and push them into an array. - Enikeyschik
  • It is possible in more detail, preferably with example code ... - Nikolay

2 answers 2

Well, personally, I would do it like this:

 public class Client { private String name; private String phone; public Client(String name, String phone) { this.name = name; this.phone = phone; } // Getters ans setters } public class DataClients { private boolean status; private String message; private List<Client> clients; public DataClients(boolean status, String message, List<Client> clients) { this.status = status; this.message = message; this.clients = clients; } // getters and setters } 

And then one could do something like this:

 List<Client> clients = new ArrayList<>(); clients.add(new Client("Vasya", "123")); clients.add(new Client("Anna", "222")); clients.add(new Client("John", "300")); DataClients dataClients = new DataClients(true, "message", clients); 

This approach will be more understandable for other programmers than to use the data collection that is incomprehensible to anyone in the array. It would also be possible to fasten the "Builder" pattern for DataClients, but this is optional ...

  • one
    Super, this is a great solution to my problem, thank you! - Nikolay
  • one
    Mark the question correctly if he helped you ... - VladimirBalun

As far as I know, there is no easy way to create such a data structure. There are a couple of workarounds that you can try.

  1. Create a map in this way:

     Map<String, Object> associativeMap = new HashMap<>(); 

    after that it can be filled in pairs like this:

     associativeMap.put("len", 3); associativeMap.put("msg", "This string hello"); associativeMap.put("data", new Object[]{"name", 3, new String[]{"Hi", "Bye"}}); 

    But in this case type checking will be lost and, thus, type safety at the compilation stage.

  2. You can go by creating a heterogeneous list (heterogenous list, HList), as described here . But this is the way for the brave (see the code for the link)

  • so pervert, as a rule, no need. but TC wants a map with arbitrary types, who knows why she needs it?) - noorhe
  • If the code for point 2 is important for the answer, then you need to add it to the answer itself. If the link to a third-party site becomes obsolete, access to the code will disappear. - Regent
  • such code, under normal conditions, is better not to write). and if anything, you can easily google it on HList Java, so you shouldn't post it here - scare people)) - noorhe