How to do the GET method from a hashmap with objects? - java

Im trying to get the id of a posto from an hashmap to compare the value in another class:
My class Posto:
public class Posto {
private int id;
private Point posicao;
private int capacidade;
private int quantidadeAtual;
private int gastoMedio;
public Posto(int id, Point posicao, int capacidade, int quantidadeAtual, int gastoMedio) {
this.id = id;
this.posicao = posicao;
this.capacidade = capacidade;
this.quantidadeAtual = quantidadeAtual;
this.gastoMedio = gastoMedio;
}
public int getPostoId() {
return id;
}
public void setPostoId(int id) {
this.id = id;
}
public Point getPostoPosicao() {
return posicao;
}
public void setPostoPosicao(Point posicao) {
this.posicao = posicao;
}
public int getPostoCapacidade() {
return capacidade;
}
public void setPostoCapacidade(int capacidade) {
this.capacidade = capacidade;
}
public int getPostoQuantidadeAtual() {
return quantidadeAtual;
}
public void setPostoQuantidadeAtual(int quantidadeAtual) {
this.quantidadeAtual = quantidadeAtual;
}
public int getPostoGastoMedio() {
return gastoMedio;
}
public void setPostoGastoMedio(int gastoMedio) {
this.gastoMedio = gastoMedio;
}
My MAIN class where i fill the hashmaps like this:
public class Main {
public static void main(String[] args) {
Central c = new Central( new Point(20, 300) );
setupCentral( c );
MenuCentral mc = new MenuCentral( c );
mc.menuPrincipal();
}
private static void setupCentral(Central c) {
//Posto p1 = new Posto(1,new Point(2,3),24,40,30);
c.addPosto(new Posto(1,new Point(10,10),10,200,180));
c.addPosto(new Posto(2,new Point(700,15),15,300,200));
}
}
And now my CENTRAL class where i have the method "addPosto" to fill the hashmap and i need the method "getPosto" to get the ids to compare in other class but i can't do it, i'm a little bit confused about the hashmaps.
public class Central {
private Point posicao;
private Map<Integer, Object> camioes = new HashMap<Integer,Object>( );
private Map<Integer,Object> postos = new HashMap<Integer,Object>( );
public Central(Point posicao) {
this.posicao = posicao;
}
public Point getPosicao() {
return posicao;
}
public void setPosicao(Point posicao) {
this.posicao = posicao;
}
public void addPosto( Posto p ){
postos.put(p.getPostoId(), p);
}
***public int getPosto (int id){
}***
}

Your Map has only one value type.
private final Map<Integer, Posto> postos = new HashMap<>();
And you only add this type.
public void addPosto( Posto p ){
postos.put(p.getPostoId(), p);
}
so it makes sense to expect this type.
public Posto getPosto(int id) {
return postos.get(id);
}
If you want to leave the Map as it is (which is a bad idea IMHO you can use an explicit cast)
public Posto getPosto(int id) {
return (Posto) postos.get(id);
}
This is needlessly verbose and error prone. At some point doing this will almost certainly lead to a bug which never needed to happen.

public Posto getPosto (int id)
{
return postos.get(id);
}

sice you are adding posto class to the hashmap use generics
private Map<Integer, Posto> camioes = new HashMap<Integer,Posto>( );
private Map<Integer,Posto> postos = new HashMap<Integer,Posto>( );
you can iterate the hashmap and get all the values
for (Integer key : camioes.keySet()) {
Posto p = postos.get(key);
System.out.println(p.getPostoId());
}
}

Related

Call an object from a map and cast directly

private static final Map<Integer, GameObject> OBJECT = new ConcurrentHashMap<>();
I have a map in which I store GameObjects, which is extended by PlayerObject, NpcObject, ItemObject.
I'm trying to create a method on which I call the object by ID and class type and cast at it directly and if it's not exists or the class of the object ID does not match the given one to return null.
So for example
final PlayerObject object = getObject(<id>, PlayerObject);
Is there any way?
Edit:
I managed to do this:
public <T extends EventObject> T getObject(final int objectId)
{
final EventObject object = OBJECT.get(objectId);
return Objects.nonNull(object) && object.getClass() == ? T (object) : null;
}
But i don't want to use Class<? extends EventObject> in parameter of this method. Can't i somehow check using the generic T if it's the same class to cast it and return or else null?
You can use Class#isInstance to check if the object's type is correct and Class#cast to convert the object to the correct type.
public static <T extends GameObject> T getObject(Integer id, Class<T> clazz) {
GameObject obj = OBJECT.get(id);
if(!clazz.isInstance(obj)) return null;
return clazz.cast(obj);
}
// ...
final PlayerObject object = getObject(<id>, PlayerObject.class);
try this complete generic method:
public static <T> T getObject(int id, Class<T> c){
Object object = OBJECT.get(id);
return object != null && object.getClass() == c ? c.cast(object) : null;
}
The other parts of the program:
private static final Map<Integer, GameObject> OBJECT = new ConcurrentHashMap<>();
public static void main(String[] args) throws ParseException {
init();
PlayerObject p = getObject(3, PlayerObject.class);
ItemObject i = getObject(3, ItemObject.class);
PlayerObject p2 = getObject(4, PlayerObject.class);
System.out.println(p);
System.out.println(i);
System.out.println(p2);
}
private static void init() {
OBJECT.put(1, new PlayerObject(1, "SomePlayer1"));
OBJECT.put(2, new PlayerObject(2, "SomePlayer2"));
OBJECT.put(3, new ItemObject(3, 5));
OBJECT.put(4, new ItemObject(4, 7));
}
GameObject.class
public class GameObject {
protected int id;
GameObject(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
PlayerObject.class
public class PlayerObject extends GameObject {
private String playerName;
PlayerObject(int id, String playerName) {
super(id);
this.playerName = playerName;
}
public String getPlayerName() {
return this.playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
#Override
public String toString() {
return "PlayerObject{\"id\": " +
this.id +
", \"playerName\": \"" +
this.playerName +
"\"}";
}
}
ItemObject.class
public class ItemObject extends GameObject {
private int itemCount;
ItemObject(int id, int itemCount) {
super(id);
this.itemCount = itemCount;
}
public int getItemCount() {
return this.itemCount;
}
public void setItemCount(int itemCount) {
this.itemCount = itemCount;
}
#Override
public String toString() {
return "ItemObject{\"id\": " +
this.id +
", \"itemCount\": " +
this.itemCount +
"}";
}
}
And the output of the program:
PlayerObject{"id": 1, "playerName": "SomePlayer1"}
ItemObject{"id": 3, "itemCount": 5}
null
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public class Stackoverflow_68734414 {
private static Map<Integer, GameObject> OBJECT_MAP = new ConcurrentHashMap<>();
public static void main(String[] args) {
PlayerObject po = new PlayerObject();
ItemObject io = new ItemObject();
OBJECT_MAP.put(1, po);
OBJECT_MAP.put(2, io);
PlayerObject p1 = getObject(1, PlayerObject.class);
PlayerObject p2 = getObject(2, PlayerObject.class);
ItemObject i1 = getObject(1, ItemObject.class);
ItemObject i2 = getObject(2, ItemObject.class);
System.out.println(p1);
System.out.println(p2);
System.out.println(i1);
System.out.println(i2);
}
public static <T extends GameObject> T getObject(Integer id, Class<T> klass){
GameObject object = OBJECT_MAP.get(id);
if(Objects.nonNull(object) && (object.getClass() == klass)) {
return klass.cast(object);
} else{
return null;
}
}
}
class GameObject{
}
class PlayerObject extends GameObject {
}
class ItemObject extends GameObject{
}
Output is as expected:
PlayerObject#179d3b25
null
null
ItemObject#254989ff
Are you looking for something similar to this:
public boolean isItemObject(int id){
GameObject obj = OBJECT.get(id)
if(obj instanceof ItemObject && obj != null){
return true;
}
return false;
}
public boolean isPlayerObject(int id){
GameObject obj = OBJECT.get(id)
if(obj instanceof PlayerObject && obj != null){
return true;
}
return false;
}
public boolean isNPCObject(int id){
GameObject obj = OBJECT.get(id)
if(obj instanceof NpcObject && obj != null){
return true;
}
return false;
}
//...
final PlayerObject pObject = isPlayerObject(objectID) ? OBJECT.get(id) : null;

ArrayList incompatible types in Java

public class GPSping {
private double pingLat;
private double pingLon;
private int pingTime;
}
The Trip class
public class Trip {
private ArrayList<GPSping> pingList;
public Trip() {
pingList = new ArrayList<>();
}
public Trip(ArrayList<GPSping> triplist) {
pingList = new ArrayList<>();
}
public ArrayList<GPSping> getPingList() {
return this.pingList;
}
public boolean addPing(GPSping p) {
int length = pingList.size();
int Time = pingList.get(length);
if (p.getTime() > this.pingList[length]) {
pinglist.add(p);
return True;
} else {
return False;
}
}
}
I am trying to add a GPS ping to this trip list but only if the time of p is after the last time in this trip list. I am very new to Java and am struggling with wrapping my head around the syntax some help would be greatly appreciated.
First element in List has index 0, to to get the last one:
int Time = pingList.get(length - 1);
But I think, it's better to store maxPingTime to check it before add new GPSping:
class Trip {
private final List<GPSping> pingList = new ArrayList<>();
private int maxPingTime = Integer.MIN_VALUE;
public List<GPSping> getPingList() {
return pingList.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(pingList);
}
public boolean addPing(GPSping p) {
if (p.getPingTime() <= maxPingTime)
return false;
pingList.add(p);
maxPingTime = p.getPingTime();
return true;
}
}
final class GPSping {
private final double pingLat;
private final double pingLon;
private final int pingTime;
public GPSping(double pingLat, double pingLon, int pingTime) {
this.pingLat = pingLat;
this.pingLon = pingLon;
this.pingTime = pingTime;
}
}
P.S. Pay attention on Encapsulation OOP principle: GPSping should be final and pingList should not be directly retrieved.

How to sort an array that is combined by "null" and Strings?

I have got an array of 20:
private Karte[] deckArr;
deckArr = new Karte[20];
Now I want to sort the array by card-names every time a new card is added.
P.S. the cards are added 1 by 1 after clicking on a button, so there are empty spaces in the array.
Since the...
Arrays.sort(deckArr.getName());
...method does not work here I asked myself how it is done.
Karte(card) class:
package Model;
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements ComparableContent<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
#Override
public boolean isLess(Karte karte) {
if (getName().compareTo(karte.getName()) < 0){
return true;
}else{
return false;
}
}
#Override
public boolean isEqual(Karte karte) {
return getName() == karte.getName();
}
#Override
public boolean isGreater(Karte karte) {
if (getName().compareTo(karte.getName()) > 0){
return true;
}else{
return false;
}
}
}
Any help is appreciated!
Why not just use ArrayList instead? Easier to add, remove elements and you will never have empty slots.
Anyway to sort you can use Collections.sort like this:
deckArr = new ArrayList<Karte>();
Collections.sort(deckArr, Comparator.comparing(karte -> karte.getName()));
Java 8 offers a simple solution:
The Comparable Interface has a static method that creates a Comaprator with an extractor.
Comparator<Card> comp = Comparator.comparing(Karte::getName);
With this using a sorting method (e.g. Arrays.sort) is easy to call.
On top of that, to solve your nullpointer problem, the Comparator Interface offers another two functions: NullsLast and nullsFirst.
Comparator<Card> comp = Comparator.nullsLast(Comparator.comparing(Card::getName));
For me this looks like the easiest solution to your question :)
This should solve your problem. Implements the Comparable interface.
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements Comparable<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
public int compareTo(Karte karte) {
return this.name.compareTo(karte.getName());
}
}
Then you just need to call Arrays.sort(deckArr);
You need to check for nulls and just call below--
Arrays.sort(deckArr, new Comparator<Karte>() {
#Override
public int compare(Karte karte1, Karte karte2) {
if (karte1.getName() == null && karte2.getName() == null) {
return 0;
}
if (karte1.getName() == null) {
return 1;
}
if (karte2.getName() == null) {
return -1;
}
return karte1.getName().compareTo(karte2.getName());
}});

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

static factory builder trouble

Needing to create an unspecified number of objects, I tried to create a builder that do that. All was well until I realized that my builder creates all objects with their properties having the same values.
So when I call the builder:
ValidationHelper v = new ValidationHelper.HelperBuilder()
.addHelper("ICAO Identifier", icaoIdentifier, rulesICAO)
.addHelper("Long Name", longName, rulesLongName)
.build();
... I'll have 2 objects and their properties will have values of the last object the builder was asked to create.
To start with, is factory builder the prudent approach to this? Secondly, is my builder salvageable?
Builder:
public class ValidationHelper {
private static ArrayList<HelperBuilder> validatorHelpers = new ArrayList();
public static class HelperBuilder {
private String txtFieldName;
private String txtFieldValue;
private List<Integer> valCodes = new ArrayList<Integer>();
private ArrayList<HelperBuilder> innerValidatorHelpers = new ArrayList<HelperBuilder>();
public HelperBuilder() {}
public final HelperBuilder addHelper(String txtFieldName, String txtFieldValue, int[] validationCodes) {
this.txtFieldName = txtFieldName;
this.txtFieldValue = txtFieldValue;
for( int i = 0; i < validationCodes.length; i++ ){
getValCodes().add((Integer) validationCodes[i]);
}
innerValidatorHelpers.add(this);
return this;
}
public final ValidationHelper build() {
return new ValidationHelper(this);
}
public String getTxtFieldName() {
return txtFieldName;
}
public String getTxtFieldValue() {
return txtFieldValue;
}
public List<Integer> getValCodes() {
return valCodes;
}
}//end HelperBuilder
private ValidationHelper(HelperBuilder helperBuilder) {
validatorHelpers = helperBuilder.innerValidatorHelpers;
}
public void setHelpers(ArrayList validatorHelpers) {
validatorHelpers = validatorHelpers;
}
public ArrayList getHelpers() {
return validatorHelpers;
}
}
EDIT/FIXED:
So for what it's worth, here's the revised builder. It needed another constructor that could properly initialize an instance of what it's supposed to build.
public class ValidationHelper {
private static ArrayList<HelperBuilder> validatorHelpers = new ArrayList();
public static class HelperBuilder {
private String txtFieldName;
private String txtFieldValue;
private List<Integer> valCodes = new ArrayList<Integer>();
private ArrayList<HelperBuilder> innerValidatorHelpers = new ArrayList<HelperBuilder>();
public HelperBuilder() {}
public HelperBuilder(String txtFieldName, String txtFieldValue, int[] validationCodes) {
this.txtFieldName = txtFieldName;
this.txtFieldValue = txtFieldValue;
for (int i = 0; i < validationCodes.length; i++) {
valCodes.add((Integer) validationCodes[i]);
}
}
public final HelperBuilder addHelper(String txtFieldName, String txtFieldValue, int[] validationCodes) {
innerValidatorHelpers.add( new HelperBuilder(txtFieldName, txtFieldValue, validationCodes) );
return this;
}
public final ValidationHelper build() {
return new ValidationHelper(this);
}
public String getTxtFieldName() {
return txtFieldName;
}
public String getTxtFieldValue() {
return txtFieldValue;
}
public List getValCodes() {
return valCodes;
}
}//end HelperBuilder
private ValidationHelper(HelperBuilder helperBuilder) {
validatorHelpers = helperBuilder.innerValidatorHelpers;
}
public ArrayList getHelpers() {
return validatorHelpers;
}
}
Each time you just overwrite the values in
private String txtFieldName;
private String txtFieldValue;
and the last one winns. So you create only 1 HelperInstance here
ValidationHelper v = new ValidationHelper.HelperBuilder()
and the fields name and value are overwritten each time you call addHelper(). But you need to create an instance for each "configuration". So addHelper should create a new Instance and add it into
private ArrayList<HelperBuilder> innerValidatorHelpers = ...;
If you want to build objects with different values you have to either
alter the builder between creating the objects so it will build something different.
instruct the builder to change the values automatically e.g. use a counter, or filename based on the date, or provide a list of values.

Categories

Resources