Im working on a school assignment, and im supposed to make a array of hashmap like this:
HashMap<String, Person>[] mood = (HashMap<String, Person>[]) new HashMap<?, ?>[6];
im reading from a file, it goes something like this. the problem is that it gives NullPointerException where i try to put the mood into mood[0]! cant find anything about how the hashmap-array works in my books.. :( would be happy for all help (:
Person p = new Person();
p.name = word[1];
p.age = word[2];
p.mood = word[3];
people.put(p.name, p);
if (p.mood.equals("HAPPY")) {
mood[0].put(p.mood, p); //NullPointerException
}
Basically, you did initialize an array of mood, but it's initialized with nulls. So before you can call any method on mood[0] (or at any other indices), you need to put a non-null object inside mood[0].
When you create arrays of objects, the array elements are initially null, so before using mood[0], you need to populate it with an instance of HashMap<String, Person>
Related
I wonder how to make a registry/database list in Java. I mean if I, for example, have a variable called "data", and then I add a new entry to that called "name" with the value "David". Then I would call something like "data.name" to get the value "David".
As seen on this picture
I've been Googling but not finding anything about it.
It sounds like you want a Map from String to String. You can use a HashMap<String,String> for that.
// Create Map using HashMap
Map<String, String> data = new HashMap<String, String>();
// Set name
data.put("name", "David");
// Get name
String name = data.get("name");
System.out.println(name);
When I create this objects, i do like this:
random_fields= new ArrayList<HashMap<String, String>>();
try {
// Getting Array of fields
JSONArray fields= json.getJSONArray("fields");
// Looping through All fields
for(int i = 0; i < fields.length(); i++) {
JSONObject jobj = fields.getJSONObject(i);
// Creating new HashMap
HashMap<String, String> map_aux = new HashMap<String, String>();
// Adding each child node to HashMap key => value
map_aux.put("field_id", jobj.getString("field_id"));
map_aux.put("field_text", jobj.getString("field_text"));
}
// Adding HashList to ArrayList
random_fields.add(map_aux);
}
And then when I try to access to every single field in the Arraylist of Hashmaps... i do like this:
For example:
editText1.setText(random_fields.get(0).get("field_text"));
and it gives me a Java Null Pointer Error... but if I do:
System.out.println(random_challenges.get(0).get("field_text"));
It works and it prints in my debug console.. the field text correctly.. Which can be the solution?
The code where you set your editText looks right. The only difference I can spot here is that you use random_challenges in your System.out.println method and random_fields in your setText method.
Would you like to provide some actual code files (not just the snippets) and I can look closer, but from what you have provided I would venture to guess that what is happening is that the values you think you are populating your hash map with (in the for loop) go out of scope and are cleaned up leaving you with the NULL reference.
You console, since it persists, keeps the data instantiated long enough for you to debug print it.
I have a json object like
{"0":"Andrew Smith"}
how can i get the value means Andrew Smith. I tried a lot but not getting.They key name will get change. I tried in this way
JsonObject jObject = new JsonObject(currentObj);
System.out.println(currentObj.toString());
Iterator i = jObject.keys();
String value = "";
while(i.hasNext()) {
String currentKey = String.valueOf(i.next());
Object currentValue = jObject.get(currentKey);
}
its not going into the loop. So how can i get the value at 0th position.
please help me. Thanks
Try to use Gson:
Map<Integer, String> map = new Gson().fromJson("{\"0\":\"Andrew Smith\"}", new TypeToken<Map<Integer, String>>(){}.getType());
System.out.println(map.entrySet().iterator().next().getValue());
Prints 'Andrew Smith'.
Get the iterator for keys and call getString for the first value
JSONObject obj = new JSONObject("{\"0\":\"Andrew Smith\"}");
Iterator<String> x = obj.keys();
if(x.hasNext())
Log.e("FACEBOOK", obj.getString(x.next()));
Your code works if you just fix all compiler errors.
i.e
It's JSONObject, not JsonObject.
currentObjis not in scope. I suppose you cut it out from somewhere where it is
but replacing it with at string literal will make it easier for other people to
test as well as eliminating one possible source of errors.
Fixing those, putting it in a method and declaring the exception made it work just
fine. Assuming whatever code you started with actually does compile I suggest checking
that the JSONObject in question really is what you think it is.
ArrayList<Persons> persList = new ArrayList<Persons>();
for(Persons p : persList){
Persons pers = new Persons();
pers = service.getPersons(id);
p.setAddress(pers.getAddress());
persList.add(pers);
}
Is this the right way to add all found Persons to persList? Thank you in advance.
No, you shouldn't modify a list while you're iterating over it, other than via the Iterator.remove method. Aside from anything else, even if this code didn't throw an exception, it would go on forever unless persList was empty... there's always be new people to iterate over!
You should basically create a new list collecting the items to add, and then use addAll at the end:
ArrayList<Persons> persList = new ArrayList<Persons>();
// Populate the list, presumably
List<Persons> extraPeople = new ArrayList<Persons>();
for(Persons p : persList){
// Note: there's no point in creating a new object only to ignore it...
Persons pers = service.getPersons(id);
p.setAddress(pers.getAddress());
extraPeople.add(pers);
}
persList.addAll(extraPeople);
This code still doesn't make much sense in my view, as you're fetching via the same id value on every iteration... I can only hope this was an example rather than real code.
Also note that if each instance of your Persons class is meant to be a single person, it would be better to call it Person.
Is there a way to add a key to a HashMap without also adding a value? I know it seems strange, but I have a HashMap<String, ArrayList<Object>> amd I want to first be able to create keys as needed and then check if a certain key exists and, if so, put the appropriate value, namely the ArrayList<Object>
Was that confusing enough?
Since you're using a Map<String, List<Object>>, you're really looking for a multimap. I highly recommend using a third-party library such as Google Guava for this - see Guava's Multimaps.
Multimap<String, Object> myMultimap = ArrayListMultimap.create();
// fill it
myMultimap.put("hello", "hola");
myMultimap.put("hello", "buongiorno");
myMultimap.put("hello", "สวัสดี");
// retrieve
List<String> greetings = myMultimap.get("hello");
// ["hola", "buongiorno", "สวัสดี"]
Java 8 update: I'm no longer convinced that every Map<K, SomeCollection<V>> should be rewritten as a multimap. These days it's quite easy to get what you need without Guava, thanks to Map#computeIfAbsent().
Map<String, List<Object>> myMap = new HashMap<>();
// fill it
myMap.computeIfAbsent("hello", ignored -> new ArrayList<>())
.addAll(Arrays.asList("hola", "buongiorno", "สวัสดี");
// retrieve
List<String> greetings = myMap.get("hello");
// ["hola", "buongiorno", "สวัสดี"]
I'm not sure you want to do this. You can store null as a value for a key, but if you do how will be able to tell, when you do a .get("key") whether the key exists or if it does exist but with a null value? Anyway, see the docs.
You can put null values. It is allowed by HashMap
You can also use a Set initially, and check it for the key, and then fill the map.
Yes, it was confusing enough ;) I don't get why you want to store keys without values instead just putting empty arraylists instead of null.
Adding null may be a problem, because if you call
map.get("somekey");
and receive a null, then you do not know, if the key is not found or if it is present but maps to null...
//This program should answer your questions
import java.util.*;
public class attemptAddingtoHashMap { //Start of program
//MAIN METHOD #################################################
public static void main(String args[]) { //main begins
Map<String, ArrayList<Object>> hmTrial = new HashMap<String, ArrayList<Object>>();
ArrayList alTrial = new ArrayList();//No values now
if (hmTrial.containsKey("first")) {
hmTrial.put("first", alTrial); }
else {hmTrial.put("first",alTrial);}
//in either case, alTrial, an ArrayList was mapped to the string "first"
//if you choose to, you can also add objects to alTrial later
System.out.println("hmTrial is " + hmTrial); //empty now
alTrial.add("h");
alTrial.add("e");
alTrial.add("l");
alTrial.add("l");
alTrial.add("o");
System.out.println("hmTrial is " + hmTrial);//populated now
} //end of main
//#############################################################################################################
} //end of class
//Note - removing objects from alTrial will remove the from the hashmap
//You can copy, paste and run this code on https://ide.geeksforgeeks.org/