Issue
I'm new to Java and Android. Arrays do not make any sense to me with so many methods.
How do I create a dynamic array that I can populate at runtime for example:
customArray[23] = 3632464346
customArray[14] = abcdefgh
customArray[22] = 2352sdfs23
Would it be best to create a JSONObject such as:
JSONObject customArray = newJSONObject();
//.....in code
customArray.put("23", 3632464346);
customArray.put("14", "abcdefgh");
customArray.put("23", "2352sdfs23");
Or is there a better way?
Solution
I think you are confusing Arrays, Maps and List.
Array has a fixed size meaning that you can put an element to a defined position only if this position is not out of its boundaries.
List are dynamic collection that looks like an array but with no real fixed size. In this case the elements are followed each other with no ways to put them in a specific position (they are some methods to bypass this constraint but it is an anti-pattern, better to use array for this case).
Maps are collection that can be seen as a JSON object. It contains a set of key value where values can be accessed from the key provided.
The only cons with Java is that collections can not have mixed type of object like we can see in Python for example. It means that if you initialize a collection of numbers, you can only put numbers value in it, same for the String object for example. It is possible to do it by setting the value type of "Object", because a String is an Object, an Integer also etc. But it need a strong verification process to not refer the wrong type to a value.
From what I understood on your question, you want to put value linked to a specific number, a HashMap is more suitable. Even if you have two differents type on your collection (Numbers and text) You can provide them as a String and convert it using the parse() method for the wanted type (e.g Integer.parseInt(String) returns an Integer)
Map<Integer, String> map = new Hashmap<>();
map.put(23, "3632464346")
map.put(14, "abcdefgh")
map.put(23, "2352sdfs23") // **This will override the first value.**
Answered By - Hamza Khattabi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.