How to make an object store itself in a hashmap - java

So I have 4 classes, Testest which has a main method, Phone which extends Product, Product and ProductDB which has a hashmap. When I make a new phone I want the phone to be stored in the database automatically.
public class Product {
protected String productID;
protected String name;
private String description;
private double price;
public Product(){
Product db = new ProductDB();
productID = this.toString();
db.add(productID, this);
}
(Getter and setter methods here...)
}
public class Phone extends Product {
private String make;
private String model;
private int storage;
public Phone(String make, String model, int storage){
this.make = make;
this.model = model;
this.storage = storage;
}
(Getter and setter methods here...)
}
import java.util.HashMap;
public class ProductDB {
private HashMap<String,Product> products = new HashMap<String, Product>();
public void add(String productID, Product product){
products.put(productID, product);
}
public void remove(String productID){
products.remove(productID);
}
public Product find(String productID){
return products.get(productID);
}
public Object showAll(){
return products.values().toArray();
}
}
public class Testest{
public static void main(String[] args){
ProductDB db = new ProductDB();
Phone phone1 = new Phone("Huwawei P30", "HP30", 50000);
Phone phone2 = new Phone("Huwawei P30 Pro", "HP30PRO", 70000);
Phone phone3 = new Phone("Samsung Galaxy SX", "SGSX", 65000);
System.out.println(db.find(phone1.productID));
System.out.println(phone1.productID);
}
}
I want this to return the object when I look for that specific id, but the problem is that the HashMap is empty for some reason
Edit I made productID private. Still nothing

It seems you want your database to include all created phones, in this case instead of creating a database each time which will be useless and also because your database is accessed from several places it will be more consistent to make your database fields and methods static and just access it from where you want:
public class ProductDB {
final private static HashMap<String,Product> products = new HashMap<String, Product>();
public static void add(String productID, Product product){
products.put(productID, product);
}
public static void remove(String productID){
products.remove(productID);
}
public static Product find(String productID){
return products.get(productID);
}
public static Object showAll(){
return products.values().toArray();
}
}
And then in Product constructor just write:
public Product{
productID = this.toString();
ProductDB.add(productID, this);
}

Related

Strategy design pattern Example?

Following is stretagy design pattern example take from here.
First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
public interface PaymentStrategy {
public void pay(int amount);
}
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
#Override
public void pay(int amount) {
System.out.println(amount +" paid with credit/debit card");
}
}
public class PaypalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PaypalStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
#Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
public class Item {
private String upcCode;
private int price;
public Item(String upc, int cost){
this.upcCode=upc;
this.price=cost;
}
public String getUpcCode() {
return upcCode;
}
public int getPrice() {
return price;
}
}
public class ShoppingCart {
//List of items
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
//pay by paypal
cart.pay(new PaypalStrategy("myemail#example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface , all which does is call a method?
1. I want to ask what is use of strategy pattern here?
The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)
2. We can directly call pay() method from there?
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?
We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
public class ShoppingCart {
// other functions
public void pay(PaymentStrategy paymentMethod, int amount){
paymentMethod.pay(amount);
}
public void payWithStrategy() {
int amount = calculateTotal();
if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal
pay(new PaypalStrategy("myemail#example.com", "mypwd"), amount);
}
else { // you really like credit card so when the money lower than the card limit, you always choose it
pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount);
}
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
cart.payWithStrategy();
}
}

How to implement a Java Hashmap with different objects as values

I want to parse a YAML-file via Jackson but encounter the problem that one of the properties (let's call it 'Event') has a string called 'type' and a 'properties' object that differs for different Events. My issue is that I need to define the POJOs for this YAML. Therefore, I want to define a Hashmap with VariableObject that can be any of some predefined classes (for brevity, let's say Shipping and Inventory).
How can I implement a Hashmap like that?
public class Event {
private static String type;
private static Map<String, VariableObject> properties;
public static void main(String[] args) {
Inventory inventory = new Inventory("inventoryName", 13);
properties.put("Inventory", inventory);
Shipping shipping = new Shipping("shippingName", true);
properties.put("Shipping", shipping);
}
}
public class Inventory {
private static String name;
private static int someNumber;
public Inventory(String name, int someNumber) {
this.name = name;
this.someNumber = someNumber;
}
}
public class Shipping {
private static String name;
private static boolean someBoolean;
public Shipping(String name, boolean someBoolean) {
this.name = name;
this.someBoolean = someBoolean;
}
}
What you're talking ablut is simple Object. It's the most specific common superclass:
private static Map<String, Object> properties;
Other solution would be to make Inventory and Shipping implement some common interface, for example Named and use it as type parameter in HashMap.
One way to do this is to make Shipping and Inventory implements the same interface (like VariableObject in your cas)
public class Event {
private static String type;
private static Map<String, VariableObject> properties;
public static void main(String[] args) {
Inventory inventory = new Inventory("inventoryName", 13);
properties.put("Inventory", inventory);
Shipping shipping = new Shipping("shippingName", true);
properties.put("Shipping", shipping);
}
}
public interface VariableObject{
//you can define common methods here if you want
}
public class Inventory implements VariableObject{
private static String name;
private static int someNumber;
public Inventory(String name, int someNumber) {
this.name = name;
this.someNumber = someNumber;
}
}
public class Shipping implements VariableObject{
private static String name;
private static boolean someBoolean;
public Shipping(String name, boolean someBoolean) {
this.name = name;
this.someBoolean = someBoolean;
}
}

Java array list in class with tickets

I've to implement Ticket class in java.
This is my code:
public class Ticket {
private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;
public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public ArrayList<Ticket> getAllTickets() {
return ticketList;
}
And my main problem is that how to do that creating an instance of Ticket class, ticketList has the newly created Ticket object. Because later I've to use public getAllTickets() method to get all tickets.
Thanks in advance!
Complete example:
package stackoverflow;
import java.math.BigDecimal;
public class Ticket {
private String name;
private BigDecimal defaultPrice;
public Ticket(String name, BigDecimal defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name =
name;
}
public BigDecimal getDefaultPrice() {
return defaultPrice;
}
public void setDefaultPrice(BigDecimal defaultPrice) {
this.defaultPrice = defaultPrice;
}
}
Event class:
package stackoverflow;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Event {
private Date date;
private List<Ticket> ticketList;
public Event(Date date) {
this.date = date;
this.ticketList = new ArrayList<>();
}
public void addTicket(Ticket ticket) {
this.ticketList.add(ticket);
}
public List<Ticket> getTicketList() {
return this.ticketList;
}
}
Main class:
package stackoverflow;
import java.math.BigDecimal;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Event eventX = new Event(new Date());
eventX.addTicket(new Ticket("ticket1", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket2", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket3", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticketPremium", new BigDecimal(100)));
for (Ticket ticket: eventX.getTicketList()) {
System.out.println("name:" + ticket.getName() + " price: " + ticket.getDefaultPrice());
}
}
}
I can't comment so I will have to just answer.
Do you mean that you need each ticket to be stored in the list whenever one is created?
If so make the constructor private and provide a factory method.
Like so:
public class Ticket {
private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;
static {
ticketList = new ArrayList<>();
}
private Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public static ArrayList<Ticket> getAllTickets() {
return ticketList;
}`
public static Ticket getInstance(String name, Float defaultPrice)
{
Ticket temp = new Ticket(name, defaultPrice);
ticketList.add(temp);
return temp;
}
Option 1
If you are trying to make sure every new ticket adds itself to its own list of tickets, this can easily be taken care of in the constructor:
public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
this.ticketList = new ArrayList<Ticket>();
this.ticketList.add(this);
}
Option 2
You could also have a separate class method to add tickets to the list, and instead use that when you initialize a new ticket. For example your Ticket class would have the following:
public void addTicketToList(Ticket ticket){
this.ticketList.add(ticket);
}
Then, when you create a new ticket you can use this:
Ticket newTicket = new Ticket();
newTicket.addTicketToList(newTicket);

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories