I am doing a school assignment where I need to add individuals to a HashMap, as well as adding "person x knows person y" to the map. We got some code form the teacher, and I modified it a bit now. But how do I add individuals to the hash map in the other class?
there are two classes
import java.util.ArrayList;
import java.util.HashMap; import java.util.List;
public class SocialGraph {
/**
* The SocialGraph class stores a social
* graph and implements * a number of methods
* to construct and query the graph.
*/
// The map that stores the social graph
private HashMap<String, List<String>> map = new HashMap<String, List<String>>();
public SocialGraph(HashMap z) { // constructor
map = z;
}
SocialGraph() { //make a default
map = ("Nobody", <"noone", "noone else" >);
}
/**
* Add individual a to this social graph.
* * Do nothing if a already exists in this social graph.
*/
public void addIndividual(String a) {
if (!map.containsKey(a)) {
map.put(a, new ArrayList<String>());
} else {
}
}
}
and also the class
public class SocialGraphTest {
public static void main (String [] args){
addIndividual one = new addIndividual ("Anne");
addIndividual two = new addIndividual ("Daisy");
addIndividual three = new addIndividual ("Bob");
addIndividual four = new addIndividual ("Charlie");
one.addKnowsArrow (two);
one.addKnowsArrow (three);
three.addKnowsArrow (two);
three.addKnowsArrow (four);
}
}
I know that a few things are wrong, but I am at my wits end... Any help is much appreciated! I read the related book chapters twice, but still do not understand it.
CodePudding user response:
Let's first start with the basics.
If you want to take a look here to understand OOP: W3s
I would suggest having an empty constructor which initializes the Map
private Map<String, List<String>> map;
public SocialGraph() {
map = new HashMap<String, List<String>>();
}
Next, you must create a method where you add the contacts of the individual.
public void addContact(String individual, String contact) {
if(map.containsKey(individual)) {
map.get(individual).add(contact);
}
// else you can throw an exception
}
And then a method to check if an individual knows a contact.
public boolean isContact(String individual, String contact) {
if(map.containsKey(individual)) {
for(String c : map.get(individual)) {
if(c.equals(contact) return true;
}
}
return false;
}
Then start from creating an object at the other class and use the method.
SocialGraph socialGraph = new SocialGraph();
socialGraph.addIndividual("Tim Davalan");
socialGraph.addContact("Tim Davalan", "Aris");
boolean isContact = socialGraph.isContact("Tim Davalan", "Aris");
This is a very simple solution, of course, you can improve your design and follow well-known practices and clean code principles.
Hope it helps and if you got any question just ask :)