Finding and changing tuples values - java

I have some tuples already made like so:
public GreenhouseControls() {
light = new Tuple<>("light", "off");
fans = new Tuple<>("fans", "off");
water = new Tuple<>("water", "off");
power = new Tuple<>("power", "on");
window = new Tuple<>("window", "good");
thermostat = new Tuple<>("thermostat","day");
}
and I'm trying to use a setVariable() method in the same class that will take in 2 string (for example, "light" and "on") and would use the first string to search the first variable of the tuple and when a match is found it would replace the second variable with the second string.
I tried adding the tuples to an ArrayList but I can't get the search part to work.
Is there a way to achieve this maybe with either an ArrayList or a HashSet?
Tuple class:
public static class Tuple<A,B> {
public final A eventName;
public final B status;
public Tuple(A eventName, B status) {
this.eventName = eventName;
this.status = status;
}
public String toString() {
return "(" + eventName + ", " + status + ")";
}
}

You can use a Map to create relationships between keys and values. In your case, a HashMap would be appropriate and would make your code much more concise and easy to read. You can use put(key,value) to set the value of a key and use get(key) to retrieve the value associated with a key.
final Map<String, String> map = new HashMap<>();
map.put("light","off");
//Etc..
//Get value
String light = map.get("light");//"off"
//Update value
map.put("light","on");
light = map.get("light");//"on"
If you are not allowed to change the structure of your code, you can implement it with your Tuple class using foreach loops like so:
import java.util.Arrays;
import java.util.List;
public class GreenhouseControls {
private final List<Tuple<String,String>> members;
public GreenhouseControls() {
members = Arrays.asList(
new Tuple<>("light", "off"),
new Tuple<>("fans", "off"),
new Tuple<>("water", "off"),
new Tuple<>("power", "on"),
new Tuple<>("window", "good"),
new Tuple<>("thermostat","day")
);
}
public void setVariable(final String eventName, final String status) {
for(final Tuple<String, String> tuple: members) {
if(tuple.getEventName().equals(eventName)) {
tuple.setStatus(status);
return;
}
}
throw new IllegalArgumentException("No event found with eventName " + eventName);
}
public String getVariable(final String eventName) {
for(final Tuple<String, String> tuple: members) {
if(tuple.getEventName().equals(eventName)) {
return tuple.getStatus();
}
}
return null;
}
public static class Tuple<A, B> {
private A eventName;
private B status;
public Tuple(final A eventName, final B status) {
this.eventName = eventName;
this.status = status;
}
#Override
public String toString() {
return "(" + eventName + ", " + status + ")";
}
public B getStatus() {
return status;
}
public void setStatus(B status) {
this.status = status;
}
public A getEventName() {
return eventName;
}
}
}

I've implemented how you could do this for a single variable of an object. i.e. "Light".
Is there a reason why you need to have a redundant variable captured as a tuple?
public class GreenhouseControls {
private String light;
public String getLightStatus() {
return light;
}
public void setLightStatus(String input)
{
if(input == "on" || input == "off")
this.light = input;
}
public static void main(String[] args)
{
GreenhouseControls controls = new GreenhouseControls();
controls.setLightStatus("on");
System.out.println(controls.getLightStatus());
controls.setLightStatus("off");
System.out.println(controls.getLightStatus());
}
}

The easier way is to use HashMap for your requirement as suggested by hev1. But if you still want to make use of the Tuple class, then here is one way of doing it.
Add getter methods to your Tuple class
public class Tuple<A,B> {
public final A eventName;
public final B status;
public Tuple(A eventName, B status) {
this.eventName = eventName;
this.status = status;
}
public String toString() {
return "(" + eventName + ", " + status + ")";
}
public A getEventName() {
return eventName;
}
public B getStatus() {
return status;
}
}
Then collect all your tuples in a List and pass it to your setVariable method. Within this method just check if the given eventName is present in any of the tuples. If yes, then remove that Tuple from the list and create a new Tuple with the given status and add it back to the list. Something like this:
void setVariable(String eventName, String status, List<Tuple>tuples) {
boolean isRemoved = tuples.removeIf(tuple -> tuple.getEventName().equals(eventName));
if(isRemoved) {
Tuple tuple = new Tuple(eventName, status);
tuples.add(tuple);
}
}
Hope this helps.

Related

Removing a map entry causes object reference within Map entry optional to change

When i retrieve a map entry from a map, store it in an optional and then remove that same entry from the map using remove(entry.getKey()) then the Optional suddenly starts pointing to the next map entry available inside the map.
Let me explain further:
I have a bunch of comment objects that i would like to sort. The comment list should always start with the comment that is accepted as the answer, it should be the first element in the list. The sort method starts with a map and uses a stream on entrySet to retrieve the first comment which has the acceptedAnswer boolean set to true.
Map<Long, CommentDTO> sortedAndLinkedCommentDTOMap = sortCommentsAndLinkCommentRepliesWithOwningComments(commentDTOSet);
Optional<Map.Entry<Long, CommentDTO>> acceptedAnswerCommentOptional = sortedAndLinkedCommentDTOMap.entrySet().stream()
.filter(entry -> entry.getValue().isAcceptedAsAnswer()).findFirst();
Lets assume that the Map contains 3 comments with ids 3, 6, and 11. The key is always the id of the comment and the comment is always the value. The comment marked as the answer has id 6. In this case the code below is executed:
if(acceptedAnswerCommentOptional.isPresent()){
Map.Entry<Long, CommentDTO> commentDTOEntry = acceptedAnswerCommentOptional.get();
sortedAndLinkedCommentDTOMap.remove(commentDTOEntry.getKey());
}
When commentDTOEntry gets initialized with the value of acceptedAnswerCommentOptional it has a reference to the accepted answer with id 6. Now, when i remove that entry from sortedAndLinkedCommentDTOMap the reference to the accepted answer comment is not only removed from sortedAndLinkedCommentDTOMap but also from acceptedAnswerCommentOptional! But instead of becoming null acceptedAnswerCommentOptional now starts pointing to the next entry of sortedAndLinkedCommentDTOMap namely the one with key 11.
I don't understand what is causing this strange behavior. Why doesn't the value of acceptedAnswerCommentOptional simply become null? And why isn't acceptedAnswerCommentOptional able to maintain the reference to the accepted answer comment when i remove it from the map?
You can see this behavior yourself when running the code in intellij IDEA using debug mode, as soon as the remove method is called the explanatory debug label for commentDTOEntry next to acceptedAnswerCommentOptional flips from 6 -> .... to 11 -> ....
EDIT: I've made a reproducible example according to WJSs wishes. This is the code:
import java.util.*;
import java.math.BigInteger;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.function.Function;
class CommentDTO implements Comparable<CommentDTO> {
private BigInteger id;
private BigInteger owningCommentId;
private BigInteger commenterId;
private Long owningEntityId;
private String commenterName;
private String commenterRole;
private String country;
private String thumbnailImageUrl;
private String content;
private String commentDateVerbalized;
private boolean flagged;
private Integer flagCount;
private boolean deleted;
private boolean liked;
private Integer likeCount;
private String lastEditedOnVerbalized;
private boolean acceptedAsAnswer;
private boolean rightToLeft;
private TreeSet<CommentDTO> replies = new TreeSet<>();
public CommentDTO() {
}
public CommentDTO(boolean acceptedAsAnswer, BigInteger id){
this.acceptedAsAnswer = acceptedAsAnswer;
this.id = id;
}
public CommentDTO(boolean acceptedAsAnswer, BigInteger id, BigInteger owningCommentId){
this.acceptedAsAnswer = acceptedAsAnswer;
this.id = id;
this.owningCommentId = owningCommentId;
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public BigInteger getOwningCommentId() {
return owningCommentId;
}
public void setOwningCommentId(BigInteger owningCommentId) {
this.owningCommentId = owningCommentId;
}
public BigInteger getCommenterId() {
return commenterId;
}
public void setCommenterId(BigInteger commenterId) {
this.commenterId = commenterId;
}
public Long getOwningEntityId() {
return owningEntityId;
}
public void setOwningEntityId(Long owningEntityId) {
this.owningEntityId = owningEntityId;
}
public String getCommenterName() {
return commenterName;
}
public void setCommenterName(String commenterName) {
this.commenterName = commenterName;
}
public String getCommenterRole() {
return commenterRole;
}
public void setCommenterRole(String commenterRole) {
this.commenterRole = commenterRole;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCommentDateVerbalized() {
return commentDateVerbalized;
}
public void setCommentDateVerbalized(String commentDateVerbalized) {
this.commentDateVerbalized = commentDateVerbalized;
}
public boolean isFlagged() {
return flagged;
}
public void setFlagged(boolean flagged) {
this.flagged = flagged;
}
public Integer getFlagCount() {
return flagCount;
}
public void setFlagCount(Integer flagCount) {
this.flagCount = flagCount;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public boolean isLiked() {
return liked;
}
public void setLiked(boolean liked) {
this.liked = liked;
}
public Integer getLikeCount() {
return likeCount;
}
public void setLikeCount(Integer likeCount) {
this.likeCount = likeCount;
}
public TreeSet<CommentDTO> getReplies() {
return replies;
}
public void setReplies(TreeSet<CommentDTO> replies) {
this.replies = replies;
}
public String getLastEditedOnVerbalized() {
return lastEditedOnVerbalized;
}
public void setLastEditedOnVerbalized(String lastEditedOnVerbalized) {
this.lastEditedOnVerbalized = lastEditedOnVerbalized;
}
public String getThumbnailImageUrl() {
return thumbnailImageUrl;
}
public void setThumbnailImageUrl(String thumbnailImageUrl) {
this.thumbnailImageUrl = thumbnailImageUrl;
}
public boolean isAcceptedAsAnswer() {
return acceptedAsAnswer;
}
public void setAcceptedAsAnswer(boolean acceptedAsAnswer) {
this.acceptedAsAnswer = acceptedAsAnswer;
}
public boolean isRightToLeft() {
return rightToLeft;
}
public void setRightToLeft(boolean rightToLeft) {
this.rightToLeft = rightToLeft;
}
#Override
public int compareTo(CommentDTO o) {
return this.id.compareTo(o.id);
}
#Override
public String toString() {
return "CommentDTO{" +
"id=" + id +
", owningCommentId=" + owningCommentId +
", commenterId=" + commenterId +
", owningEntityId=" + owningEntityId +
", commenterName='" + commenterName + '\'' +
", commenterRole='" + commenterRole + '\'' +
", country='" + country + '\'' +
", thumbnailImageUrl='" + thumbnailImageUrl + '\'' +
", content='" + content + '\'' +
", commentDateVerbalized='" + commentDateVerbalized + '\'' +
", flagged=" + flagged +
", flagCount=" + flagCount +
", deleted=" + deleted +
", liked=" + liked +
", likeCount=" + likeCount +
", lastEditedOnVerbalized='" + lastEditedOnVerbalized + '\'' +
", acceptedAsAnswer=" + acceptedAsAnswer +
", rightToLeft=" + rightToLeft +
", replies=" + replies +
'}';
}
}
public class HelloWorld implements Comparable<HelloWorld> {
private Long id;
private boolean acceptedAsAnswer;
public HelloWorld(){}
public HelloWorld(boolean acceptedAsAnswer, Long id){
this.acceptedAsAnswer = acceptedAsAnswer;
this.id = id;
}
#Override
public String toString() {
return "id= " + id + " acceptedAsAnswer= " + acceptedAsAnswer;
}
public boolean isAcceptedAsAnswer(){
return acceptedAsAnswer;
}
public long getId(){
return id;
}
public static void main(String []args){
HelloWorld helloWorld = new HelloWorld();
helloWorld.doTest();
}
#Override
public int compareTo(HelloWorld o) {
return this.id.compareTo(o.id);
}
public void doTest(){
Set<CommentDTO> commentDTOSet = new HashSet<>();
commentDTOSet.add( new CommentDTO(false, BigInteger.valueOf(3)));
commentDTOSet.add( new CommentDTO(true, BigInteger.valueOf(6)));
commentDTOSet.add( new CommentDTO(false, BigInteger.valueOf(11)));
commentDTOSet.add( new CommentDTO(true, BigInteger.valueOf(7), BigInteger.valueOf(6)));
commentDTOSet.add( new CommentDTO(true, BigInteger.valueOf(8), BigInteger.valueOf(6)));
Map<Long, CommentDTO> sortedAndLinkedCommentDTOMap = sortCommentsAndLinkCommentRepliesWithOwningComments(commentDTOSet);
Optional<Map.Entry<Long, CommentDTO>> acceptedAnswerCommentOptional = sortedAndLinkedCommentDTOMap.entrySet().stream()
.filter(entry -> entry.getValue().isAcceptedAsAnswer()).findFirst();
if(acceptedAnswerCommentOptional.isPresent()){
Map.Entry<Long, CommentDTO> commentDTOEntry = acceptedAnswerCommentOptional.get();
System.out.println(commentDTOEntry.toString());
sortedAndLinkedCommentDTOMap.remove(commentDTOEntry.getKey());
System.out.println(commentDTOEntry.toString());
}
}
private Map<Long, CommentDTO> sortCommentsAndLinkCommentRepliesWithOwningComments(Set<CommentDTO> commentDTOSet){
Map<Long, CommentDTO> commentDTOMap = commentDTOSet.stream()
.collect(Collectors.toMap(comment -> comment.getId().longValueExact(), Function.identity(), (v1,v2) -> v1, TreeMap::new));
commentDTOSet.forEach(commentDTO -> {
BigInteger owningCommentId = commentDTO.getOwningCommentId();
if(owningCommentId != null){
CommentDTO owningCommentDTO = commentDTOMap.get(owningCommentId.longValueExact());
owningCommentDTO.getReplies().add(commentDTO);
}
});
commentDTOMap.values().removeIf(commentDTO -> commentDTO.getOwningCommentId() != null);
return commentDTOMap;
}
}
You can run the code above here: https://www.tutorialspoint.com/compile_java_online.php
EDIT 2: example code reproduces my problem now.
EDIT 3:
This line of code
commentDTOMap.values().removeIf(commentDTO -> commentDTO.getOwningCommentId() != null);
is causing the observed behavior. The accepted answer (commentDTO with id 6) has 2 replies to it. Those 2 comments (with id 7 and 8) are 'owned' by CommentDTO 6 and are also referenced by the replies list inside CommentDTO 6. At the end of sortCommentsAndLinkCommentRepliesWithOwningComments() I remove all CommentDTOs that can be considered replies to another comment owningCommentId != null. I do this because these comments are now referenced from within the replies lists of the owning comments. If i were to leave them in the original map then those replies will appear twice. Therefore i remove them but this is causing unexpected behavior. I would like to know why this is so.
That happens because the map you are using is a TreeMap.
A TreeMap is implemented as a red-black tree, which is a self-balancing binary tree.
The entries of the map are used as the nodes of the tree.
If you remove one entry then the tree has to re-balance itself and it might happen that the entry is then used to point to the node that takes its place.
Since TreeMap.entrySet() is backed by the map, the changes are reflected in the set.
The changes depends also on which node you are removing, for example if it's a leaf then it might just be unlinked from the tree and the entry is left unaffected.
If you use another map implementation like an HashMap then you won't get this behavior.
By the way, here's a simpler example, which doesn't even involve Optional or custom classes:
Map<Long, String> map = new TreeMap<>();
map.put(1L, "a");
map.put(2L, "b");
map.put(3L, "c");
map.put(4L, "d");
map.put(5L, "e");
map.put(6L, "f");
Map.Entry<Long, String> entry = map.entrySet().stream()
.filter(e -> e.getKey().equals(4L))
.findFirst()
.get();
System.out.println(entry); // prints 4=d
map.remove(entry.getKey());
System.out.println(entry); // prints 5=e

Create map of maps from eclipse toString()

Eclipse can auto-generate a toString() method from a object's fields. If those fields are objects then they too may have similarly auto-generated toString() methods.
e.g. a President object might look like this:
President [country=USA, name=Name [title=Mr, forename=Barack, surname=Obama], address=Address [houseNumber=1600, street=Pennsylvania Avenue, town=Washington]]
which is easier to read if I format it:
President [
country=USA,
name=Name [
title=Mr,
forename=Barack,
surname=Obama],
address=Address [
houseNumber=1600,
street=Pennsylvania Avenue,
town=Washington]]
What is the best way to parse this String to create a map of maps?
I've got a solution, but it's not pretty. I was hoping to be able to avoid the low level String manipulation somehow, but here it is:
import java.util.LinkedHashMap;
import java.util.Map;
public class MappedObject {
public String className;
public Map<String, String> leafFields = new LinkedHashMap<>();
public Map<String, MappedObject> treeFields = new LinkedHashMap<>();
#Override
public String toString() {
return "[className=" + className
+ (leafFields.isEmpty() ? "" : ", leafFields=" + leafFields)
+ (treeFields.isEmpty() ? "" : ", treeFields=" + treeFields)
+ "]";
}
public static MappedObject createFromString(String s) {
MappedObject mo = new MappedObject();
new Mapper(s).mapObject(mo);
return mo;
}
private static class Mapper {
private String s;
public Mapper(String s) {
this.s = s;
}
private String mapObject(MappedObject mo) {
mo.className = removeFirstNCharacters(s.indexOf(' '));
while (s.contains("=")) {
removeLeadingNonLetters();
String key = removeFirstNCharacters(s.indexOf('='));
removeFirstNCharacters(1); // remove the =
String leafValue = getLeafValue();
if (leafValue != null) {
mo.leafFields.put(key, leafValue);
if (s.startsWith("]")) { // that was the last field in the tree
return s;
}
} else {
MappedObject treeField = new MappedObject();
mo.treeFields.put(key, treeField);
s = new Mapper(s).mapObject(treeField);
}
}
return s; // s contains only close brackets - ]
}
private void removeLeadingNonLetters() {
int i = 0;
while (!Character.isLetter(s.charAt(i))) {
i++;
}
removeFirstNCharacters(i);
}
private String removeFirstNCharacters(int n) {
String value = s.substring(0, n);
s = s.substring(value.length());
return value;
}
private String getLeafValue() {
int endIndex = getEndIndex();
if (!s.contains("[") || s.indexOf('[') > endIndex) {
return removeFirstNCharacters(endIndex);
}
return null;
}
/** The end of the value, if it's a leaf field. */
private int getEndIndex() {
if(s.contains(",")) {
return Math.min(s.indexOf(','), s.indexOf(']'));
}
return s.indexOf(']');
}
}
}

(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;
}

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.

Enum within enum

I want to create an enum within an enum for sql query in java. For example I want to say table.create and it would return CREATE TABLE or database.create and it would return CREATE DATABASE. How can I do this?
enum SQL {
table("ALTER,CREATE"),
database("CREATE");
}
Define an enum within the enum:
public static enum SQL {
table(Command.ALTER,Command.CREATE),
database(Command.CREATE);
public static enum Command {
CREATE,
ALTER
}
private final Command[] commands;
private SQL (Command... commands) {
this.commands = commands;
}
public Command[] getCommands() {
return commands;
}
}
Although you can do this, it would be better to declare the Command enum in its own class/file. I haven't seen anyone declare an enum inside another enum before... I almost like it.
Why make it an enum within an enum?
Table.java
public enum Table {
CREATE("CREATE TABLE"),
ALTER("ALTER TABLE");
private String cmd;
Table(String cmd) {
this.cmd = cmd;
}
#Override
public String toString() {
return cmd;
}
}
Database.java
public enum Database {
CREATE("CREATE DATABASE");
private String cmd;
Database(String cmd) {
this.cmd = cmd;
}
#Override
public String toString() {
return cmd;
}
}
With this example, System.out.println(Table.CREATE); prints CREATE TABLE.
This will also aid in readabilty becuase you can produce code like:
String query = Table.CREATE + "(Column1 " + DbType.INTEGER + " " + Column.UNIQUE + " " + Column.PRIMARY_KEY + ")";
Which would be a bit easier to read and understand, IMO.
EDIT
To attempt to get close to what you're after you could do something like:
public enum SQL {
TABLE("TABLE", SQL.CREATE_FLAG | SQL.ALTER_FLAG),
DATABASE("DATABASE", SQL.CREATE_FLAG);
public static final int CREATE_FLAG = 1;
public static final int ALTER_FLAG = 2;
public static final String CREATE_STRING = "CREATE";
public static final String ALTER_STRING = "ALTER";
public static final String INVALID = "INVALID";
private String name;
private boolean create;
private boolean alter;
SQL(String name, int flags) {
create = (flags & CREATE_FLAG) != 0;
alter = (flags & ALTER_FLAG) != 0;
this.name = name;
}
public String create() {
if (create)
return CREATE_STRING + " " + name;
else
return INVALID;
}
public String alter() {
if (alter)
return ALTER_STRING + " " + name;
else
return INVALID;
}
}
Where you can call:
System.out.println(SQL.TABLE.create()); // CREATE TABLE
System.out.println(SQL.TABLE.alter()); // ALTER TABLE
System.out.println(SQL.DATABASE.alter()); // INVALID
System.out.println(SQL.DATABASE.create()); // CREATE DATABASE

Categories

Resources