Java inheritance issue - java

I am new to programming and I am having an issue with my program that should return this output:
Portfolio #00001, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
Portfolio #00002, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
Portfolio #00001, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
Portfolio #00002, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
Portfolio #00001, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
Portfolio #00002, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
Portfolio #00001, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
Portfolio #00002, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
Currently, my program is not returning anything. Could someone please help?
Here are the classes :
DisplayElement Interface :
public interface DisplayElement {
public void display();
}
Observer Interface :
public interface Observer {
public void update (Map<String,Double> priceMap);
}

You need to register your protfolios after their creation, and before calling setPrices(), as required by the observer pattern: Your program should be like :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
interface DisplayElement {
void display();
}
interface Observer {
void update (Map<String,Double> priceMap);
}
class PricesDisplay implements Observer, DisplayElement {
private String ticker;
private double price;
private Subject PriceData;
Map<String,Double> priceMap;
PricesDisplay(Subject PriceData) {
this.PriceData = PriceData;
}
PricesDisplay(String ticker, Subject PriceData) {
this.ticker = ticker;
this.PriceData = PriceData;
}
public void update(Map<String,Double> priceMap) {
this.priceMap = priceMap;
display();
}
public void display() {
for (Map.Entry<String, Double> entry : priceMap.entrySet()) {
System.out.printf("\nPortfolio #%s, " + "%s = " + "%.2f, ",
ticker, entry.getKey(), entry.getValue());
}
}
}
interface Subject{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
void measurementsChanged();
void setPrices(Map<String,Double> priceMap);
}
class PriceData implements Subject {
private ArrayList observers;
PriceData priceData;
private Map<String,Double> priceMap = new HashMap<String,Double>();
PriceData() {
observers = new ArrayList();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(priceMap);
}
}
public void measurementsChanged() {
notifyObservers();
}
public void setPrices(Map<String,Double> priceMap) {
this.priceMap = priceMap;
measurementsChanged();
}
}
class Test {
private static Map<String,Double> priceMap = new HashMap<String,Double>();
private static PriceData priceData = new PriceData();
public static void main(String[] args) {
// establish two portfolios as listeners for priceData.
// for now, we assume that both portfolios contain the same
// collection of investments.
PricesDisplay firstPortfolio =
new PricesDisplay("00001", priceData);
PricesDisplay secondPortfolio =
new PricesDisplay("00002", priceData);
priceData.registerObserver(firstPortfolio);
priceData.registerObserver(secondPortfolio);
generateInitialPrices();
updatePrices(.02);
updatePrices(-.05);
updatePrices(.06);
}
static void generateInitialPrices()
{
priceMap.put("ASD", 42.50);
priceMap.put("BDM", 52.50);
priceMap.put("CAC", 22.20);
priceMap.put("DFAS", 45.00);
priceData.setPrices(priceMap);
}
static void updatePrices(double changePercent)
{
for( String key : priceMap.keySet())
{
double v = priceMap.get(key) * (1.0 + changePercent);
priceMap.put(key, v);
}
priceData.setPrices(priceMap);
}
}

setPrices should be :
public <map> void setPrices(Map<> priceMap) {
this.priceMap = priceMap; // <-- missing line
measurementsChanged();
}

Related

Android java, Dao interface in the database class seems to be weird

I was recently learning Room Database but this code seems too weird.
I tried to understand this line of code but maybe my google search skill isn't that good.
Can you explain this?
public abstract NoDoDao noDoDao();
The thing I don't understand, how Interface which is 'NoDoDa' here, can be called as if it were 'method' or 'function'? This is my first time seeing this syntax. And why is there also 'Abstract keyword'?
package com.paige.room.data;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.paige.room.model.NoDo;
#Database(entities = {NoDo.class}, version = 1)
public abstract class NoDoRoomDatabase extends RoomDatabase {
//Don't want to create a lot of instances, singleton
//volatile means "don't store in the cache"
private static volatile NoDoRoomDatabase INSTANCE;
public abstract NoDoDao noDoDao();
public static NoDoRoomDatabase getDatabase(final Context context){
if(INSTANCE == null){
//synchronized keyword, for UI Thread, force it to work as it is supposed to do
synchronized (NoDoRoomDatabase.class){
if(INSTANCE == null){
//create our db
INSTANCE = Room.databaseBuilder(
context,
NoDoRoomDatabase.class,
"nodo_database")
.addCallback(roomDatabaseCallBack)
.build();
}
}
}
return INSTANCE;
}
//callback
private static RoomDatabase.Callback roomDatabaseCallBack =
new RoomDatabase.Callback(){
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
new PopulateDBAsync(INSTANCE).execute();
}
};
private static class PopulateDBAsync extends AsyncTask<Void, Void, Void> {
private final NoDoDao noDoDao;
PopulateDBAsync(NoDoRoomDatabase db) {
this.noDoDao = db.noDoDao();
}
#Override
protected Void doInBackground(Void... voids) {
// noDoDao.deleteAll(); //removes all items from our table
// //for testing
// NoDo noDo = new NoDo("Buy a new Ferrari");
// noDoDao.insert(noDo);
//
// noDo = new NoDo("Buy a Big House");
// noDoDao.insert(noDo);
return null;
}
}
}
This is my entire code
NoDoDao is an abstract class, it cannot be instantiated (constructed) but the class can be used. Which is what is happening here.
What you may not be aware of is that Room generates code and it is these abstractions that allow the underlying code to be implemented on your behalf.
Say for example that you Entity class NoDO is :-
#Entity
public class NoDo {
#PrimaryKey
Long id;
}
And your Dao class NoDoDao is :-
#Dao
public abstract class NoDoDao {
#Query("SELECT * FROM nodo")
abstract List<NoDo> getnothing();
}
And you compile (F9) then you get :-
Looking at NoDoDao_Impl then you get :-
public final class NoDoDao_Impl extends NoDoDao {
private final RoomDatabase __db;
public NoDoDao_Impl(RoomDatabase __db) {
this.__db = __db;
}
#Override
List<NoDo> getnothing() {
final String _sql = "SELECT * FROM nodo";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final List<NoDo> _result = new ArrayList<NoDo>(_cursor.getCount());
while(_cursor.moveToNext()) {
final NoDo _item;
_item = new NoDo();
if (_cursor.isNull(_cursorIndexOfId)) {
_item.id = null;
} else {
_item.id = _cursor.getLong(_cursorIndexOfId);
}
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
}
That is the real getNothing code has been generated by the annotation processor.
As important is that the NoDoRoomDatabase_Impl is :-
public final class NoDoRoomDatabase_Impl extends NoDoRoomDatabase {
private volatile NoDoDao _noDoDao;
#Override
protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {
final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(configuration, new RoomOpenHelper.Delegate(1) {
#Override
public void createAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("CREATE TABLE IF NOT EXISTS `NoDo` (`id` INTEGER, PRIMARY KEY(`id`))");
_db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
_db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '1fdde93d9c60610ae88bf0c74771844a')");
}
#Override
public void dropAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("DROP TABLE IF EXISTS `NoDo`");
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onDestructiveMigration(_db);
}
}
}
#Override
protected void onCreate(SupportSQLiteDatabase _db) {
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onCreate(_db);
}
}
}
#Override
public void onOpen(SupportSQLiteDatabase _db) {
mDatabase = _db;
internalInitInvalidationTracker(_db);
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onOpen(_db);
}
}
}
#Override
public void onPreMigrate(SupportSQLiteDatabase _db) {
DBUtil.dropFtsSyncTriggers(_db);
}
#Override
public void onPostMigrate(SupportSQLiteDatabase _db) {
}
#Override
protected RoomOpenHelper.ValidationResult onValidateSchema(SupportSQLiteDatabase _db) {
final HashMap<String, TableInfo.Column> _columnsNoDo = new HashMap<String, TableInfo.Column>(1);
_columnsNoDo.put("id", new TableInfo.Column("id", "INTEGER", false, 1, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysNoDo = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesNoDo = new HashSet<TableInfo.Index>(0);
final TableInfo _infoNoDo = new TableInfo("NoDo", _columnsNoDo, _foreignKeysNoDo, _indicesNoDo);
final TableInfo _existingNoDo = TableInfo.read(_db, "NoDo");
if (! _infoNoDo.equals(_existingNoDo)) {
return new RoomOpenHelper.ValidationResult(false, "NoDo(a.so59478461.NoDo).\n"
+ " Expected:\n" + _infoNoDo + "\n"
+ " Found:\n" + _existingNoDo);
}
return new RoomOpenHelper.ValidationResult(true, null);
}
}, "1fdde93d9c60610ae88bf0c74771844a", "1d145662ebde2538a8da3217996c0550");
final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context)
.name(configuration.name)
.callback(_openCallback)
.build();
final SupportSQLiteOpenHelper _helper = configuration.sqliteOpenHelperFactory.create(_sqliteConfig);
return _helper;
}
#Override
protected InvalidationTracker createInvalidationTracker() {
final HashMap<String, String> _shadowTablesMap = new HashMap<String, String>(0);
HashMap<String, Set<String>> _viewTables = new HashMap<String, Set<String>>(0);
return new InvalidationTracker(this, _shadowTablesMap, _viewTables, "NoDo");
}
#Override
public void clearAllTables() {
super.assertNotMainThread();
final SupportSQLiteDatabase _db = super.getOpenHelper().getWritableDatabase();
try {
super.beginTransaction();
_db.execSQL("DELETE FROM `NoDo`");
super.setTransactionSuccessful();
} finally {
super.endTransaction();
_db.query("PRAGMA wal_checkpoint(FULL)").close();
if (!_db.inTransaction()) {
_db.execSQL("VACUUM");
}
}
}
#Override
public NoDoDao noDoDao() {
if (_noDoDao != null) {
return _noDoDao;
} else {
synchronized(this) {
if(_noDoDao == null) {
_noDoDao = new NoDoDao_Impl(this);
}
return _noDoDao;
}
}
}
}
See how NoDoDao has been overridden to basically be NoDoDao_Impl

Translating basic Actionscript game code into Java?

I have been trying to translate this tutorial into Java code, as I want to make a simple game with level/achievements in android (and haven't found as thorough/basic examples in java online, if you have one please share)
Please help me understand:
How can I link different file of classes together? in the example they don't seem to refer to each other? Basically how can I pass on the properties and settings from the tasks/games to these functions which are elsewhere in the code? do I just refer to the class several times throughout the code?
For example I am stuck in this part, could use help in understanding how this works in java code? (examples are most appreciated)
> private var mProps :Object; // dictionary of properties
private var mAchievements :Object; // dictionary of achievements
public function Achieve() {
mProps = { };
mAchievements = { };
}
public function defineProperty(theName :String, theInitialValue :int, theaActivationMode :String, theValue :int) :void {
mProps[theName] = new Property(theName, theInitialValue, theaActivationMode, theValue);
}
public function defineAchievement(theName :String, theRelatedProps :Array) :void {
mAchievements[theName] = new Achievement(theName, theRelatedProps);
}
Remember that each class must go to its own file.
public class Property {
private String mName;
private int mValue;
private String mActivation;
private int mActivationValue;
private int mInitialValue;
public Property(String theName, int theInitialValue, String theActivation, int theActivationValue) {
mName = theName;
mActivation = theActivation;
mActivationValue = theActivationValue;
mInitialValue = theInitialValue;
}
public int getValue() {
return mValue;
}
public void setValue(int n) {
mValue = n;
}
public boolean isActive() {
boolean aRet = false;
switch(mActivation) {
case Achieve.ACTIVE_IF_GREATER_THAN: aRet = mValue > mActivationValue; break;
case Achieve.ACTIVE_IF_LESS_THAN: aRet = mValue < mActivationValue; break;
case Achieve.ACTIVE_IF_EQUALS_TO: aRet = mValue == mActivationValue; break;
}
return aRet;
}
public String getActivation() {
return mActivation;
}
}
import java.util.ArrayList;
public class Achievement {
private String mName; // achievement name
private ArrayList<String> mProps; // array of related properties
private boolean mUnlocked; // achievement is unlocked or not
public Achievement(String theId, ArrayList<String> theRelatedProps) {
mName = theId;
mProps = theRelatedProps;
mUnlocked = false;
}
public boolean isUnlocked() {
return mUnlocked;
}
public void setUnlocked(boolean b) {
mUnlocked = b;
}
public ArrayList<String> getProps() {
return mProps;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Achieve {
// activation rules
public static final String ACTIVE_IF_GREATER_THAN = ">";
public static final String ACTIVE_IF_LESS_THAN = "<";
public static final String ACTIVE_IF_EQUALS_TO = "==";
private HashMap<String,Property> mProps; // dictionary of properties
private HashMap<String,Achievement> mAchievements; // dictionary of achievements
public Achieve() {
mProps = new HashMap<String,Property>();
mAchievements = new HashMap<String,Achievement>();
}
public void defineProperty(String theName, int theInitialValue, String theaActivationMode, int theValue) {
mProps.put(theName, new Property(theName, theInitialValue, theaActivationMode, theValue));
}
public void defineAchievement(String theName, ArrayList<String> theRelatedProps) {
mAchievements.put(theName, new Achievement(theName, theRelatedProps));
}
public int getValue(String theProp) {
Property p = mProps.get(theProp);
if (p != null) return p.getValue();
return 0;
}
public void setValue(String theProp, int theValue) {
Property p = mProps.get(theProp);
if (p == null) return;
switch(p.getActivation()) {
case Achieve.ACTIVE_IF_GREATER_THAN:
theValue = theValue > p.getValue() ? theValue : p.getValue();
break;
case Achieve.ACTIVE_IF_LESS_THAN:
theValue = theValue < p.getValue() ? theValue : p.getValue();
break;
}
p.setValue(theValue);
}
public void addValue(ArrayList<String> theProps, int theValue) {
for (int i = 0; i < theProps.size(); i++) {
String aPropName = theProps.get(i);
setValue(aPropName, getValue(aPropName) + theValue);
}
}
public ArrayList<Achievement> checkAchievements() {
ArrayList<Achievement> aRet = new ArrayList<Achievement>();
Iterator<Map.Entry<String,Achievement>> it = mAchievements.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String,Achievement> pair = it.next();
Achievement aAchievement = pair.getValue();
if (!aAchievement.isUnlocked()) {
int aActiveProps = 0;
ArrayList<String> props = aAchievement.getProps();
for (int p = 0; p < props.size(); p++) {
Property aProp= mProps.get(props.get(p));
if (aProp.isActive()) {
aActiveProps++;
}
}
if (aActiveProps == props.size()) {
aAchievement.setUnlocked(true);
aRet.add(aAchievement);
}
}
}
return aRet;
}
}

Learning Java - function returns 0

I'm just learning Java... I have three classes which creates bank account
My first class;
public class Banka {
protected static int pocetUctu = 0;
public Ucet vytvorUcet(Clovek maj, double pocatecni) {
Ucet uc = new Ucet(maj, pocatecni);
pocetUctu++;
System.out.println("Ucet " + uc + " vytvoren");
System.out.println("Pocet uctu " + pocetUctu);
return uc;
}
public static void main(String[] args) {
Banka b1 = new Banka();
Clovek pn = new Clovek("Petr Novotny", 1949);
Clovek jv = new Clovek("Jan Vesely", 1970);
Ucet pu1 = b1.vytvorUcet(pn, 1000);
Ucet pu2 = b1.vytvorUcet(pn, 50000);
Ucet ju = b1.vytvorUcet(jv, 3000);
pu2.prevedNa(ju, 1000);
ju.prevedNa(pu1, 500);
pu1.vypisInfo();
pu2.vypisInfo();
ju.vypisInfo();
}
}
My second class;
public class Clovek {
protected String jmeno;
protected int rokNarozeni;
protected static int pocetLidi = 0;
public Clovek(String j, int rN) {
jmeno = j;
rokNarozeni = rN;
pocetLidi++;
}
public void vypisInfo() {
System.out.println("Clovek:");
System.out.println("Jmeno="+jmeno);
System.out.println("Rok narozeni="+rokNarozeni);
}
}
My third class;
public class Ucet {
static double zustatek;
static Clovek majitel;
public Ucet(Clovek maj, double zus) {
maj = majitel;
zus = zustatek;
}
public void pridej(double pocatecni) {
zustatek += pocatecni;
}
public void vypisZustatek() {
System.out.println(zustatek);
}
public Ucet prevedNa(Ucet kam, float castka) {
zustatek -= castka; // nebo také vhodné je: pridej(-castka);
kam.pridej(castka);
return this;
}
public void vypisInfo() {
System.out.println("Vlastník" + majitel);
System.out.println("Zůstatek" + zustatek);
}
}
pu1.vypisInfo(); should output account owner and his money on it, but It shows owner null and balance 0. Where can be problem ?
Assignment is from right to left
majitel = maj;
zustatek = zus;
You have:
public Ucet(Clovek maj, double zus) {
maj = majitel;
zus = zustatek;
}
But you should have:
public Ucet(Clovek maj, double zus) {
majitel = maj;
zustatek = zus;
}

Hashmap overwriting values

Hey im trying to make a hashMap store for planes. But when i add, it will only print out one flight. Can anyone help me with this.
Here is my code:
import java.util.Scanner;
public class MainApp
{
private Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
Airline aerLingus = new Airline("AerLingus");
PlaneStore planeStore = new PlaneStore("Aer Lingus");
Flight p1 = new Flight("Aer Lingus","A01", 150.5, 10.5, 500, Flight.AIRPLANETYPE.AIRBUS);
Flight p2 = new Flight("Aer Lingus","B01", 50.3, 1.5, 91, Flight.AIRPLANETYPE.CORPORATE);
Flight p3 = new Flight("Aer Lingus","C01", 12.2, -3.1, 56, Flight.AIRPLANETYPE.AIRBUS);
Flight p4 = new Flight("Ryan Air","D01", 10.5, 1.5, 430, Flight.AIRPLANETYPE.PRIVATE);
Flight p5 = new Flight("Ryan Air","E01", 0.3, 2.1, 101, Flight.AIRPLANETYPE.CORPORATE);
Flight p6 = new Flight("Ryan Air","F01", 2.2, -3, 291, Flight.AIRPLANETYPE.AIRBUS);
planeStore.addFlight("",p1);
planeStore.addFlight("",p2);
planeStore.addFlight("",p3);
planeStore.print();
aerLingus.add(planeStore);
aerLingus.add(planeStore);
aerLingus.add(planeStore);
aerLingus.printPlane();
}
}
import java.util.TreeMap;
public class PlaneStore
{
private String airlineName;
private TreeMap<String,Flight> planeMap;
public PlaneStore(String airlineName)
{
this.airlineName = "";
planeMap = new TreeMap<String,Flight>();
}
public String getAirlineName() {
return airlineName;
}
public TreeMap<String, Flight> getFlightList() {
return planeMap;
}
public void addFlight(String airline,Flight flight)
{
planeMap.put(airline, flight);
}
// ---------------------------------------------------------------------------------------
// Name: Print.
// ---------------------------------------------------------------------------------------
public void print()
{
System.out.println("\n********Student's in the Company.********");
for (Flight flight : planeMap.values()) {
// System.out.println(employee); to print the toString of Employee
// class
// or:
System.out.println("Airline:\t" + flight.getAirline());
System.out.println("Flight Number:\t" + flight.getFlightNumber());
System.out.println("Fuel Remaining:\t" + flight.getFuelRemaining());
}
}
}
public class Flight
{
private String airline;
private String flightNumber;
private double fuelRemaining;
private double overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
}
public Flight(String airline, String flightNumber, double fuelRemaining,
double overdue, int passengerNumber, AIRPLANETYPE planeType)
{
super();
this.airline = airline;
this.flightNumber = flightNumber;
this.fuelRemaining = fuelRemaining;
this.overdue = overdue;
this.passengerNumber = passengerNumber;
this.planeType = planeType;
}
public String getAirline() {
return airline;
}
public void setAirline(String airline) {
this.airline = airline;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public double getOverdue() {
return overdue;
}
public void setOverdue(double overdue) {
this.overdue = overdue;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public String toString()
{
return "Flight [airline=" + airline + ", flightNumber=" + flightNumber
+ ", fuelRemaining=" + fuelRemaining + ", overdue=" + overdue
+ ", passengerNumber=" + passengerNumber + ", planeType="
+ planeType + "]";
}
}
HashMap is a data structure in which you are able to store key-value pairs. It essential that the key is unique. Otherwise you overwrite the value that has the same key.
With this data structure you are able to add and find values very quickly because the complexity of adding and finding values is constant. But the disadvantage is that you can only add a key one time.
EDIT in response to further code posting:
Every time you do PlaneStore.addPlane() you are providing a blank key. A Hashmap is only useful if you provide a unique key for every object. Otherwise every plane will overwrite the previous plane. This is why when you print you only see a single object. Give every plane a unique key, possibly a tail number or something related, and you should be able to retrieve every object.
You need to define your hashmap as follows:
Map<String, List<Flight>> map = new TreeMap<String, List<Flight>>();
and then for each flight name you need to create a new list of flights as follows:
map.get("foo") = new ArrayList<Flight>();
map.get("foo").add(Flight);
for above code, you need to be defensive, if there is no list, you need to create one, otherwise you ll get some exception. moreover, ensure that only one list will be created per flight key.

issues with implementing command pattern in Java

I was trying to do a simple implementation of the command patter in java. However, I am getting the following error:
java.lang.ClassNotFoundException: AddCommand
Exception in thread "main" java.lang.NullPointerException
at com.programming.sample.TransactionCommand.execute(TestTransactionCommand.java:64)
at com.programming.sample.CommandManager.runCommands(TestTransactionCommand.java:33)
at com.programming.sample.TestTransactionCommand.main(TestTransactionCommand.java:124)
Code:
package com.programming.sample;
//TestTransactionCommand.java
import java.util.*;
final class CommandReceiver {
private int[] c;
private CommandArgument a;
private CommandReceiver(){
c = new int[2];
}
private static CommandReceiver cr = new CommandReceiver();
public static CommandReceiver getHandle() {
return cr;
}
public void setCommandArgument(CommandArgument a) {
this.a = a;
}
public void methAdd() {
c = a.getArguments();
System.out.println("The result is " + (c[0]+c[1]));
}
public void methSubtract() {
c = a.getArguments();
System.out.println("The result is " + (c[0]-c[1]));
}
}
class CommandManager {
private Command myCommand;
public CommandManager(Command myCommand) {
this.myCommand = myCommand ;
}
public void runCommands( ) {
myCommand.execute();
}
}
class TransactionCommand implements Command {
private CommandReceiver commandreceiver;
private Vector commandnamelist,commandargumentlist;
private String commandname;
private CommandArgument commandargument;
private Command command;
public TransactionCommand () {
this(null,null);
}
public TransactionCommand ( Vector commandnamelist, Vector
commandargumentlist){
this.commandnamelist = commandnamelist;
this.commandargumentlist = commandargumentlist;
commandreceiver = CommandReceiver.getHandle();
}
public void execute( ) {
for (int i = 0; i < commandnamelist.size(); i++) {
commandname = (String)(commandnamelist.get(i));
commandargument = (CommandArgument)((commandargumentlist.get(i)));
commandreceiver.setCommandArgument(commandargument);
String classname = commandname + "Command";
try {
Class cls = Class.forName(classname);
command = (Command) cls.newInstance();
}
catch (Throwable e) {
System.err.println(e);
}
command.execute();
}
}
}
class AddCommand extends TransactionCommand {
private CommandReceiver cr;
public AddCommand () {
cr = CommandReceiver.getHandle();
}
public void execute( ) {
cr.methAdd();
}
}
class SubtractCommand extends TransactionCommand {
private CommandReceiver cr;
public SubtractCommand () {
cr = CommandReceiver.getHandle();
}
public void execute( ) {
cr.methSubtract();
}
}
class CommandArgument {
private int[] args;
CommandArgument() {
args = new int[2];
}
public int[] getArguments() {
return args;
}
public void setArgument(int i1, int i2) {
args[0] = i1; args[1] = i2;
}
}
public class TestTransactionCommand {
private Vector clist,alist;
public TestTransactionCommand() {
clist = new Vector();
alist = new Vector();
}
public void clearBuffer(Vector c, Vector a) {
clist.removeAll(c);
alist.removeAll(a);
}
public Vector getClist() {
return clist;
}
public Vector getAlist() {
return alist;
}
public static void main(String[] args) {
CommandArgument ca,ca2;
TestTransactionCommand t = new TestTransactionCommand();
ca = new CommandArgument();
ca.setArgument(2,8);
Vector myclist = t.getClist();
Vector myalist = t.getAlist();
myclist.addElement("Add");
myalist.addElement(ca);
TransactionCommand tc = new TransactionCommand(myclist,myalist);
CommandManager cm = new CommandManager(tc);
cm.runCommands();
t.clearBuffer(myclist,myalist);
ca2 = new CommandArgument();
ca2.setArgument(5,7);
myclist = t.getClist();
myalist = t.getAlist();
myclist.addElement("Subtract");
myalist.addElement(ca2);
myclist.addElement("Add");
myalist.addElement(ca2);
TransactionCommand tc2 = new TransactionCommand(myclist,myalist);
CommandManager cm2 = new CommandManager(tc2);
cm2.runCommands();
}
}
I guess, this is where it's failing.
try {
Class cls = Class.forName(classname);
command = (Command) cls.newInstance();
}
catch (Throwable e) {
System.err.println(e);
}
command.execute();
Obviously, the class AddCommand wasn't found in the classpath, so it resulted in the ClassNotFoundException, which you ignored with just System.err.println(e); and then trying to invoke command.execute();. The object command isn't initialized to an instance.
Perhaps, providing the full class name, like, com.programming.sample.AddCommand, would fix it.
When you create the classname, the string contains only AddCommand. The class' actual name is com.programming.sample.AddCommand.
I can't compile your code - there is no Command interface.
With simple
interface Command {
public void execute();
}
your code compiles fine just with warning:
Note: D:\dev\puzzles\TestTransactionCommand.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Categories

Resources