Get java object by id - java

What I am trying to achieve is to update an object's value with only his ID known:
How can I get the object with a corresponding ID?
So that I can update a property?
class forest
public class forest {
public forestName;
public forest(String forestName){
this.forestName=forestName;
}
updateTreeName(int id, String Name){
// Here I need to update the name of the tree with that specific ID
}
public static void main(String[] args) {
forest greenforest = new forest();
// create some tree's in the greenforest.
greenforest.updateTreeName(4, "red leafe");
}
}
class tree
public class tree {
public String treeName;
public int id;
public tree(int id, String treeName){
this.treeName=treeName;
this.id=id;
}
}

Use HashMap to keep objects. Then use the get method to get the object with the given id.
public class Forest {
public String forestName;
HashMap<Integer, Tree> trees = new HashMap<>();
public Forest(String forestName){
this.forestName=forestName;
//initialize trees
trees.put(4, new Tree(4, "redleaef"));
}
public void updateTreeName(int id, String Name){
trees.get(id).treeName = Name;
}
public static void main(String[] args) {
Forest greenforest = new Forest("name");
// create some tree's in the greenforest.
greenforest.updateTreeName(4, "red leafe");
}
}

Related

Static Objects are not getting stored in HashMap.!

I am trying to create a Map with key as a String and Value as a static class. But when I am printing the data, it only stores the last key-value pair. Can someone help me with this.
import java.util.HashMap;
import java.util.Map;
public class MapImplementation {
public static class Asset {
public static String assetName;
public static String assetType;
private void setAssetName(String name) {
Asset.assetName = name;
}
private void setAssetType(String type) {
Asset.assetType = type;
}
private String getAssetName() {
return assetName;
}
private String getAssetType() {
return assetType;
}
}
public static void main(String[] args) {
Map<String, Asset> map = new HashMap<>();
Asset asset1 = new Asset();
asset1.setAssetName("Vodafone");
asset1.setAssetType("STOCK");
map.put("Vodafone", asset1);
Asset asset2 = new Asset();
asset2.setAssetName("Google");
asset2.setAssetType("STOCK");
map.put("Google", asset2);
Asset asset3 = new Asset();
asset3.setAssetName("IBM");
asset3.setAssetType("BOND");
map.put("IBM", asset3);
for (String str : map.keySet()) {
Asset ast = map.get(str);
System.out.println(ast.getAssetName()+" "+ast.getAssetType());
}
}
}
The output I am getting is:
IBM BOND
IBM BOND
IBM BOND
Change:
public static String assetName;
public static String assetType;
to:
public String assetName;
public String assetType;
static fields are class level, not instance level - they are shared across all instances. Even though you are calling setters of different objects, the exact same 2 fields are being updated in those methods.

Java Vector: Each element contains three objects. How to operate based on the value of one of them?

For example, I have vector(object1, object2, price). How can I print elements where price > 100?
All the tutorials and documents (concerning operating in such way) I have seen only handle vectors where each element contains only one object.
So how can I get a handle on one specific object inside element? Or is this even possible?
A side question: what are those called? That is, if a single element is comprised of several items, what are those items called? Like in databases, a record is comprised of fields. Hard to google stuff you do not know the name of.
Main:
import java.util.Vector;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String type;
String location;
double value;
System.out.print("type->");
type=sc.nextLine();
System.out.print("location->");
location=sc.nextLine();
Property prop=new Property(type,location);
System.out.print("value->");
value=sc.nextDouble();
InsuranceInfo insu=new InsuranceInfo(prop,value);
container.addInsuranceInfo(insu);
}
InsInfoContainer class:
public class InsInfoContainer {
private Vector<InsuranceInfo> container;
public InsInfoContainer() {
container = new Vector<>(3, 1);
}
public void addInsuranceInfo(InsuranceInfo insu) {
container.addElement(insu);
}
public void print() {
Iterator<InsuranceInfo> iter = container.iterator();
while (iter.hasNext()) {System.out.println(iter.next());}
}
InsuranceInfo class:
public class InsuranceInfo {
public InsuranceInfo(Property prop, double value) {
this.prop = prop;
this.value = value;
}
private Property prop;
private double value;
public Property getProp() {return prop;}
public void setProp(Property prop) {this.prop = prop;}
public double getValue() {return value;}
public void setValue(double value) {this.value= value;}
}
Property class:
public class Property {
private String type;
private String location;
public Property(final String type, final String location) {
this.type = type;
this.location = location;
}
public String getType() {return this.type;}
public void setType(final String type) {this.type = type;}
public String getLocation() {return this.location;}
public void setLocation(final String sijainti) {this.location = location;}
}
You have a container to store your InsuranceInfo:
private Vector<InsuranceInfo> container;
Your container is called Collection
Your InsuranceInfo instances inside your container are called element
Your "items" inside InsuranceInfo (Property, value) are called property or field of element
To iterate over your container collection, the usual ways are using for loop or foreach loop:
public void print() {
for (InsuranceInfo element: container) {
if (element.getValue() > 100) { // Here is your condition to filter elements
// Process your elements here
}
}
}
You can also use Iterator, Stream to do that.

What Pattern design to get rid of the type casting in my case?

public abstract class Employee {
String name;
String position
public Employee(String name, String position) {
this.name = name;
this.position = position
}
}
public class Pilot extends Employee {
public Pilot(String name,String position) {
super();
}
public void flight() {//flight the plane}
//getter and setter for the fields
}
public class Attendance extends Employee {
public Attendance(String name,String position) {
super();
}
public Food servingFood(String foodName) {}
}
// there will be many other positions
public class Company {
HashMap<String, ArrayList<Employee>> employeeTable; //values is a list of workers, key is the position
public Company() {this.employeeTable = new HashMap<>();}
public initializeEmployeeTable(file) {} //read file, and create keys in map (file contains information of the position)
public Worker hireEmployee(String position, String name){
if (position.equals("pilot")) {
Pilot p = Pilot(name);
employeeTable.get("pilot").add(p);
return p
}
else if (position.equals("flightAttendance")) {// the else if statement continuous to check the other position; }
}
public Worker callEmployee(String position, String name) {
for ( Employee e : employeeTable.get(position) ) {
if e.getName().equals(name) {
return e;
}
}
return null;
}
public static void main(String[] args) {
Company company = new Company();
company.initializeEmployeeTable(filePath);
File eventFile = new File(filePath); // event file describes what's happening in real world; read the lines, and call the program so that program simulates the real world events
sc = new Scanner(eventFile);
do {
String currentEvent = sc.nextLine();
String[] currentEventParts = currentEvent.split(", ");
if (currentEvent[0].equals("New Airplane")) { // currentEvent looks like {"New Airplane", "Attendance"// this part can be other position name, "Linda"}
Worker w = company.hireEmployee(currentEventParts[1], currentEventParts[2]); }
else if ((currentEvent[0].equals("flying"))) {
Worker w = company.callEmployee(currentEvent[0], currentEvent[1])
if (w.getPosition().equals("Pilot")) {(Worker) w.flight()}
if (w.getPosition().equals("Attendance")) {(Worker) w.serveFood()}
}
}
The reason there is HashMap for employee because there will be many positions; and reading the event file (when the first index is "New Airplane"); I don't want to go check the following index (would be name and position) with so many if statements to create corresponding employee. But when comes to calling specific methods, I need type casting now; since each method can be different (different type parameter, return type); so it's not ideal to have this methods be abstract method in super class employee and have the subclass implements the body.
Any advices: employee data structure; reading file strategy, pattern design would be appreciated. thanks

Java create array of classes within class from outside static class

I would like to create an instance of a class, that has an array of class members within it where the array is defined in length upon initialization. The code I have written does not contain any errors precompile, but after running returns nullPointerException. I want to be able to access products of class storeA by typing storeA.products[productnumber].(product variable), is this possible?
package tinc2;
public class FirstProgram {
public static void main(String[] args) {
store storeA = new store();
storeA.name = "Walmart";
storeA.products = new store.product[3];
storeA.products[0].name = "Horses";
System.out.println(storeA.products[0].name);
}
public static class store{
String name;
product products[];
static class product{
String name;
int quantity;
double price;
}
}
}
Go for
public static void main(String[] args) {
store storeA = new store();
storeA.name = "Walmart";
storeA.products = new store.product[3];
storeA.products[0] = new store.product();
storeA.products[0].name = "Horses";
System.out.println(storeA.products[0].name);
}
instead.
Besides you should place those classes in separate files.
You should follow naming conventions in Java, e.g. Store instead of store.
You should use getters and setters.
I would avoid statics, if it is possible.
You should not be instantiating a static class. Your Product class should not be defined as static. I recommend:
package tinc2;
public class FirstProgram {
public static void main(String[] args) {
Store.name = "Walmart";
Store.products = new Product[1];
Store.products[0] = new Product();
Store.products[0].name = "Horses";
System.out.println(Store.products[0].name);
}
public static class Store{
String name;
Product products[];
}
public class Product{
String name;
int quantity;
double price;
}
}

HashMap change Values Object

I have a set with String and i want to create hash map with String key and Node Object value.
and this is my code
Set<String> cities = new HashSet<>();
Map<String, Node> allCity = new HashMap<>();
Iterator<String> c = cities.iterator();
while(c.hasNext()){
String name = c.next();
Node cit = new Node(name);
allCity.put(name, cit);
}
my problem is when i read first from c iterator and correctly make new object and put it to hash map but when second object was create in my hash map the previous object value was change like this
first read
key = "New York"
Value = Node (and the value of node is New York)
second read
Key = "Los Angles"
Value = Node (and the value of node is Los Angles)
and my first read Value with New York key was change to Los Angles.
myNode class
public class Node{
private static String city;
private static double pathCost;
private ArrayList<Edge> neighbours;
private Node parent;
public Node(String cityName){
city = cityName;
neighbours = new ArrayList<>();
}
public static String getValue() {
return city;
}
public static void setValue(String city) {
Node.city = city;
}
public static double getPathCost() {
return pathCost;
}
public static void setPathCost(double pathCost) {
Node.pathCost = pathCost;
}
public static String getCity() {
return city;
}
public static void setCity(String city) {
Node.city = city;
}
public ArrayList<Edge> getNeighbours() {
return neighbours;
}
public void setNeighbours(ArrayList<Edge> neighbours) {
this.neighbours = neighbours;
}
public void addNeighbours(Edge n){
this.neighbours.add(n);
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
#Override
public String toString() {
return city;
}
}
Please help me.
That's because you made the city (and pathCost) fields static. A static field belongs to the class, not to a specific instance of this class. Each node has a specific city, so you want to mek the city field an instance field, and not a static field.
Read the Java tutorial about class members.
The city member in your Node class is static. This means all the Nodes share the same city, and when one instance updates it (e.g., in the constructor), the change applies for all of them.
To resolve this issue, you could change city to be an instance member:
public class Node{
private String city;
...
Without looking thoroughly there is a major mistake here:
private static String city;
city is node (i.e. instance) data and should not be static.
Since it is static in your case, all nodes share one value for city, which most probably isn't what you want. The same applies to pathCost.

Categories