Goal:
Represent subset of Strings created from Strings defined in abstract class
test if string on input belongs to given subset
Initial solution:
Let's have list of possible events.
/**
* List of events.
*/
public abstract class EventKeys {
public static final String KEY_EVENT_1 = "EVENT_1";
public static final String KEY_EVENT_2 = "EVENT_2";
public static final String KEY_EVENT_3 = "EVENT_3";
public static final String KEY_EVENT_4 = "EVENT_4";
public static final String KEY_EVENT_5 = "EVENT_5";
public static final String KEY_EVENT_6 = "EVENT_6";
public static final String KEY_EVENT_7 = "EVENT_7";
//etc ..
}
I want make subset of these events for example events 1,3,5 and only for these events allow some action. The goal is make method boolean isEventAllowed(String eventKey) which will say if event belongs to subset of allowed events.
The really naive way to do this is:
/**
* Allow only events 1,3,5
*/
private isEventAllowed(String eventKey) {
if(eventKey.equals(EventKeys1.KEY_EVENT_1)) {
return true;
} else if(eventKey.equals(EventKeys1.KEY_EVENT_3)) {
return true;
} else if(eventKey.equals(EventKeys1.KEY_EVENT_3)) {
return true;
} else {
return false;
}
}
The I feel this approach is not very convinient. I need better way to represent the subset of strings and provide action does input string belongs to defined subset?
Other possible solutions:
As other options i was thinking about other two options, but I'm still not sure if its good way to do it.
1)enum - create enum of strings
Put in enum: EventKeys1.KEY_EVENT_1, EventKeys1.KEY_EVENT_2, EventKeys1.KEY_EVENT_3
Test does String keyEvent belons to defined enum?
2) list
create list List<String> subset and put there
EventKeys1.KEY_EVENT_1, EventKeys1.KEY_EVENT_2, EventKeys1.KEY_EVENT_3
test if String keyEvent belongs to list subset
PLEASE READ THIS BEFORE ANSWER:
class EventKeys is given, can't be changed, main set of options
I need somehow represent subset
I need advice for better implementation of method isAllowedEvent(String keyEvent) which returns true if input string
belongs to defined subset
How about something like this?
private boolean isEventAllowed(String eventKey) {
return Arrays.asList(KEY_EVENT_1, KEY_EVENT_3, KEY_EVENT_5).contains(eventKey);
}
Readability could be improved following John Fergus' comment by using something like this:
private static List<String> SUBSET = Arrays.asList(KEY_EVENT_1, KEY_EVENT_3, KEY_EVENT_5);
private boolean isEventAllowed(String eventKey) {
return SUBSET.contains(eventKey);
}
While a Set holding the allowed values is usually the preferred option, there are also possible syntactical improvements for your original code which you should become aware of, as their general pattern applies to other situations as well.
A statement like
if(condition1)
action;
else if(condition2)
/* (same) */ action;
…
is redundant and may be replaced by
if(condition1 || condition2)
action;
…
similarly
if(condition)
return true;
else
return false;
is redundant and may (or even should) be replaced by
return condition;
Putting both together, your original code becomes
private boolean isEventAllowed(String eventKey) {
return eventKey.equals(EventKeys1.KEY_EVENT_1)
|| eventKey.equals(EventKeys1.KEY_EVENT_3)
|| eventKey.equals(EventKeys1.KEY_EVENT_5);
}
Alternatively, you can use a switch statement:
private boolean isEventAllowed(String eventKey) {
switch(eventKey) {
case EventKeys1.KEY_EVENT_1:
case EventKeys1.KEY_EVENT_3:
case EventKeys1.KEY_EVENT_5:
return true;
default:
return false;
}
}
Not everyone likes this coding style, but that’s more an issue of project or company policies. There are situation, where such a switch statement still is the cleanest solution. One advantage over if statements and even the Set approach is that the compiler will immediately shout if you mistakenly name the same constant twice rather than the intended constant (a typical copy&paste error), like you do in your third if statement where you use KEY_EVENT_3 instead of the intended KEY_EVENT_5…
I have a general test, call it
public void generalTest(boolean var1, boolean var2) {
if (var1) {
...
} else {
...
}
if (var2) {
...
} else {
...
}
}
I have a class level int countNumber initialized to 0; Then I do this
#Test(enabled = true, dataProvider = "getEmptyPhone", invocationCount = 4)
public void test(TextContext context) {
countNumber++;
boolean v1 = countNumber < 3;
boolean v2 = (countNumber % 2) == 0
generalTest(v1, v2);
}
countNumber increases each time so I get a combination of all booleans. The one thing is that the dataProvider is kind of complicated and it does a lot of soap messaging. Once I run it, I can use the same data in the other three tests, but in the above the data provider is called each time. Is there a way I can have it just do the data provider the first time? I know I could just have one test and put like for (boolean v : new boolean[] { true, false}), but that way if the test fails, the later ones will not be executed. Some tests could pass even if others didn't. So is there a way to do this?
I suppose it would also be too much to ask also if I could use the "description" keyword, and make countNumber be part of it so the test failure would show which iteration?
As a fairly green Java coder I've set myself the hefty challenge of trying to write a simple text adventure. Unsurprisingly, I've encountered difficulties already!
I'm trying to give my Location class a property to store which exits it contains. I've used a boolean array for this, to essentially hold true/false values representing each exit. I'm not entirely convinced that
a) this is the most efficient way to do this and
b) that I'm using the right code to populate the array.
I would appreciate any and all feedback, even if it is for a complete code over-haul!
At present, when instantiating a Location I generate a String which I send through to the setExits method:
String e = "N S U";
secretRoom.setExits(e);
In the Location class, setExits looks like this:
public void setExits(String e) {
if (e.contains("N"))
bexits[0] = true;
else if (e.contains("W"))
bexits[1] = true;
else if (e.contains("S"))
bexits[2] = true;
else if (e.contains("E"))
bexits[3] = true;
else if (e.contains("U"))
bexits[4] = true;
else if (e.contains("D"))
bexits[5] = true;
}
I'll be honest, I think this looks particularly clunky, but I couldn't think of another way to do it. I'm also not entirely sure now how to write the getExits method...
Any help would be welcome!
The most efficient and expressive way is the following:
Use enums as Exits and use an EnumSet to store them. EnumSet is an efficient Set implementation that uses a bit field to represent the enum constants.
Here is how you can do it:
public enum Exit { North, West, South, East, Up, Down; }
EnumSet<Exit> set = EnumSet.noneOf(Exit.class); // An empty set.
// Now you can simply add or remove exits, everything will be stored compactly
set.add(Exit.North); // Add exit
set.contains(Exit.West); // Test if an exit is present
set.remove(Exit.South); //Remove an exit
Enum set will store all exits in a single long internally, so your code is expressive, fast, and saves a lot of memory.
Is there any reason why you are doing this with Strings and aren't passing in booleans, i.e.
public void setExits(boolean N, boolean E, boolean S, boolean W, boolean U, boolean D)
Or having setters?
public void setNorthOpen(boolean open)
{
bexits[4] = open;
}
Secondly, why are you storing the exits as an array of booleans, it's a small finite set, why not just
boolean N,S,E,W,U,D;
As then you don't need to keep track of which number in the array each direction is.
Also
This is a correct answer (if not completely optimal like that of #gexicide) but I fully encourage anyone to look at the other answers here for an interesting look at how things can be done in Java in different ways.
For future reference
Code which works belongs on Code Review, not Stack Overflow. Although as #kajacx pointed out, this code shouldn't -in fact- work.
OK, first of all, your setExits() method will not work as intended, chained if-elseif will maximally execute 1 branch of code, for example:
if (e.contains("N"))
bexits[0] = true;
else if (e.contains("W"))
bexits[1] = true;
Even if e contains both N and W, only bexits[0] will be set. Also this method will only add exits (for example calling setExits("") will not delete any existing exits.
I would change that method to:
bexits[0] = e.contains("N");
bexits[1] = e.contains("W");
...
Also, i definetly wouldn't remember that north is on index 0, west in on 1, ... so a common practice is to name your indexes using final static constants:
public static final int NORTH = 0;
public static final int WEST = 1;
...
Then you can write in your setExits method:
bexits[NORTH] = e.contains("N");
bexits[WEST] = e.contains("W");
...
(much more readible)
Finally, if you want your code even more well-arranged, you can make a Exits class representing avaliable exits, and backed by boolean array. Then on place where you create your String, you could create this class instead and save yourself work with generating and then parsing a string.
EDIT:
as #gexicide answers, there is a really handy class EnumSet which would be probably better for representing the exits than bollean array.
The EnumSet in the other answer is the best way to do this, I just wanted to add one more thing though for the future when you start looking not just at whether you can move but where you are moving to.
As well as EnumSet you also have EnumMap.
If you define a Room class/interface then inside the Room class you can have
Map<Direction, Room> exits = new EnumMap<>(Direction.class);
You can now add your links into the map as follows:
exits.put(Direction.NORTH, theRoomNorthOfMe);
Then your code to move between rooms can be very general purpose:
Room destination=currentRoom.getExit(directionMoved);
if (destination == null) {
// Cannot move that way
} else {
// Handle move to destination
}
I would create an Exit enum and on the location class just set a list of Exit objects.
so it would be something like:
public enum Exit { N, S, E, W, U, D }
List<Exit> exits = parseExits(String exitString);
location.setExits(exits);
Given what your code looks like, this is the most readable implementation I could come up with:
public class Exits {
private static final char[] DIRECTIONS = "NSEWUD".toCharArray();
public static void main(String... args) {
String input = "N S E";
boolean[] exits = new boolean[DIRECTIONS.length];
for(int i = 0; i< exits.length; i++) {
if (input.indexOf(DIRECTIONS[i]) >= 0) {
exits[i] = true;
}
}
}
}
That being said, there's a number of cleaner solutions possible. Personally I would go with enums and an EnumSet.
By the way, your original code is incorrect, as it will set as most one value in the array to true.
If you're defining exits as a string, you should use it. I would do it like:
public class LocationWithExits {
public static final String NORTH_EXIT="[N]";
public static final String SOUTH_EXIT="[S]";
public static final String EAST_EXIT="[E]";
public static final String WEST_EXIT="[W]";
private final String exitLocations;
public LocationWithExits(String exitLocations) {
this.exitLocations = exitLocations;
}
public boolean hasNorthExit(){
return exitLocations.contains(NORTH_EXIT);
}
public static void main(String[] args) {
LocationWithExits testLocation=new LocationWithExits(NORTH_EXIT+SOUTH_EXIT);
System.out.println("Has exit on north?: "+testLocation.hasNorthExit());
}
}
using array of booleans might cause a lot of problems if you forget what exactly means bexits[0]. Os it for north or south? etc.
or you can just use enums and list of exits available . Then in methid test if list contain a certain enum value
Personally, I think you can hack it around a bit using an enum and turn the following:
public void setExits(String e) {
if (e.contains("N"))
bexits[0] = true;
else if (e.contains("W"))
bexits[1] = true;
else if (e.contains("S"))
bexits[2] = true;
else if (e.contains("E"))
bexits[3] = true;
else if (e.contains("U"))
bexits[4] = true;
else if (e.contains("D"))
bexits[5] = true;
}
into
public enum Directions
{
NORTH("N"),
WEST("W"),
SOUTH("S"),
EAST("E"),
UP("U"),
DOWN("D");
private String identifier;
private Directions(String identifier)
{
this.identifier = identifier;
}
public String getIdentifier()
{
return identifier;
}
}
and then do:
public void setExits(String e)
{
String[] exits = e.split(" ");
for(String exit : exits)
{
for(Directions direction : Directions.values())
{
if(direction.getIdentifier().equals(exit))
{
bexits[direction.ordinal()] = true;
break;
}
}
}
}
Although after having written it down, I can't really tell you if it's that much better. It's easier to add new directions, that's for sure.
All the approaches listed in the answeres are good. But I think the approach you need to take depends on the way you are going to use the exit field. For example if you are going to handle exit as strings then Ross Drews approach would require a lot of if-else conditions and variables.
String exit = "N E";
String[] exits = exit.split(" ");
boolean N = false, E = false, S = false, W = false, U = false, D = false;
for(String e : exits){
if(e.equalsIgnoreCase("N")){
N = true;
} else if(e.equalsIgnoreCase("E")){
E = true;
} else if(e.equalsIgnoreCase("W")){
W= true;
} else if(e.equalsIgnoreCase("U")){
U = true;
} else if(e.equalsIgnoreCase("D")){
D = true;
} else if(e.equalsIgnoreCase("S")){
S = true;
}
}
setExits(N, E, S, W, U, D);
Also if you have an exit and you want to check whether a location has that particular exit then again you will have to do the same
public boolean hasExit(String exit){
if(e.equalsIgnoreCase("N")){
return this.N; // Or the corresponding getter method
} else if(e.equalsIgnoreCase("E")){
return this.E;
} else if(e.equalsIgnoreCase("W")){
return this.W;
} else if(e.equalsIgnoreCase("U")){
return this.U;
} else if(e.equalsIgnoreCase("D")){
return this.D;
} else if(e.equalsIgnoreCase("S")){
return this.S;
}
}
So if you are going to manipulate it as a string, in my opinion the best approach would be to go for list and enum. By this way you could do methods like hasExit, hasAnyExit, hasAllExits, hasNorthExit, hasSouthExit, getAvailableExits etc etc.. very easily. And considering the number of exits (6) using a list (or set) wont be an overhead. For example
Enum
public enum EXIT {
EAST("E"),
WEST("W"),
NORTH("N"),
SOUTH("S"),
UP("U"),
DOWN("D");
private String exitCode;
private EXIT(String exitCode) {
this.exitCode = exitCode;
}
public String getExitCode() {
return exitCode;
}
public static EXIT fromValue(String exitCode) {
for (EXIT exit : values()) {
if (exit.exitCode.equalsIgnoreCase(exitCode)) {
return exit;
}
}
return null;
}
public static EXIT fromValue(char exitCode) {
for (EXIT exit : values()) {
if (exit.exitCode.equalsIgnoreCase(String.valueOf(exitCode))) {
return exit;
}
}
return null;
}
}
Location.java
import java.util.ArrayList;
import java.util.List;
public class Location {
private List<EXIT> exits;
public Location(){
exits = new ArrayList<EXIT>();
}
public void setExits(String exits) {
for(char exitCode : exits.toCharArray()){
EXIT exit = EXIT.fromValue(exitCode);
if(exit != null){
this.exits.add(exit);
}
}
}
public boolean hasExit(String exitCode){
return exits.contains(EXIT.fromValue(exitCode));
}
public boolean hasAnyExit(String exits){
for(char exitCode : exits.toCharArray()){
if(this.exits.contains(EXIT.fromValue(exitCode))){
return true;
}
}
return false;
}
public boolean hasAllExit(String exits){
for(char exitCode : exits.toCharArray()){
EXIT exit = EXIT.fromValue(exitCode);
if(exit != null && !this.exits.contains(exit)){
return false;
}
}
return true;
}
public boolean hasExit(char exitCode){
return exits.contains(EXIT.fromValue(exitCode));
}
public boolean hasNorthExit(){
return exits.contains(EXIT.NORTH);
}
public boolean hasSouthExit(){
return exits.contains(EXIT.SOUTH);
}
public List<EXIT> getExits() {
return exits;
}
public static void main(String args[]) {
String exits = "N E W";
Location location = new Location();
location.setExits(exits);
System.out.println(location.getExits());
System.out.println(location.hasExit('W'));
System.out.println(location.hasAllExit("N W"));
System.out.println(location.hasAnyExit("U D"));
System.out.println(location.hasNorthExit());
}
}
Why not this if you want a shorter code:
String symbols = "NWSEUD";
public void setExits(String e) {
for (int i = 0; i < 6; i++) {
bexits[i] = e.contains(symbols.charAt(i));
}
}
If you want a generic solution you can use a map, which maps from a key (in your case W, S, E.. ) to a corresponding value (in your case a boolean).
When you do a set, you update the value the key is associated with. When you do a get, you can take an argument key and simply retrieve the value of the key. This functionality does already exist in map, called put and get.
I really like the idea of assigning the exits from a String, because it makes for brief and readable code. Once that's done, I don't see why you would want to create a boolean array. If you have a String, just use it, although you might want to add some validation to prevent accidental assignment of strings containing unwanted characters:
private String exits;
public void setExits(String e) {
if (!e.matches("[NSEWUD ]*")) throw new IllegalArgumentException();
exits = e;
}
The only other thing I would add is a method canExit that you can call with a direction parameter; e.g., if (location.canExit('N')) ...:
public boolean canExit(char direction) {
return exits.indexOf(direction) >= 0;
}
I like enums, but using them here seems like over-engineering to me, which will rapidly become annoying.
**Edit**: Actually, don't do this. It answers the wrong question, and it does something which doesn't need to be done. I just noticed #TimB's answer of using a map (an EnumMap) to associate directions with rooms. It makes sense.
I still feel that if you only need to track exit existence, a String is simple and effective, and anything else is over-complicating it. However, only knowing which exits are available isn't useful. You will want to go through those exits, and unless your game has a very plain layout it won't be doable for the code to infer the correct room for each direction, so you'll need to explicitly associate each direction with another room. So there seems to be no actual use for any method "setExits" which accepts a list of directions (regardless of how it's implemented internally).
public void setExits(String e)
{
String directions="NwSEUD";
for(int i=0;i<directions.length();i++)
{
if(e.contains(""+directions.charAt(i)))
{
bexits[i]=true;
break;
}
}
}
the iterative way of doing the same thing..
Long chains of else if statements should be replaced with switch statements.
Enums are the most expressive way to store such values as long as the efficiency is not a concern. Keep in mind that enum is a class, so creation of a new enum is associated with corresponding overhead.
PerformanceTest1:
public class PerformanceTest1 {
public static void main(String[] args) {
boolean i = false;
if (i == false)
i = true;
System.out.println(i);
}
}
PerformanceTest2:
public class PerformanceTest2 {
public static void main(String[] args) {
boolean i = false;
i = true;
System.out.println(i);
}
}
I've been asking myself about these two possibilities, what would give the best performance. I don't know if the fact of checking if (i == false) (at PerformanceTest1) every time while(true) loop is executed would give a worse performance than just setting i = true every time the while(true) loop is executed.
Q: So, PerformanceTest1 or PerformanceTest2 would give a best performance? Why?
EDIT:
So, based on the answers, I suppose that the performance of the code below would be the same too?
public class PerformanceTest1 {
public static void main(String[] args) {
Point i;
if (i == null)
i = new Point();
}
}
public class PerformanceTest2 {
public static void main(String[] args) {
Point i;
i = new Point();
}
}
The branch predictor would just ignore the path which is executing the if inside the while after few iterations so there will be no difference, as the condition will be always false.
The CPU will keep its execution as assuming that the if is not taken and by getting a 100% prediction hit. So there will be no rollback and the two becomes basically equivalent.
Just as a side note, there's no need to have i == false, !i is enough.
There is no real difference in terms of performance between the two methods.
The first if-test will only be executed once. This is because the JVM (Java Virtual Machine) will not perform the test after a few times as i will always be true. I'm no expert on the JVM and runtime, but you might even expect the if-test to only run once.
They both will have the same performance, but I believe that the PerformanceTest1 might take up more performance, since you are doing an extra operation. it takes less performance to simply assign a value to a boolean variable, than checking if it equals to false first
I am working on a project in which I need to return true if my current datacenter is either DC1, DC2 or DC3 only not DEV by looking at the enum as mentioned below. And if is not then return false.
With the use of Below code, I can find my machine name. And my machine name looks like this -
tps1143.dc1.host.com
tps1142.dc2.host.com
tps1442.dc3.host.com
Below is my code -
public enum DatacenterEnum {
DEV, DC1, DC2, DC3;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
private static final String getHostName() {
try {
return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
} catch (UnknownHostException e) {
// log error
}
return null;
}
}
Below is my main method -
public static void main(String[] args) {
System.out.println(DatacenterEnum.getHostName());
}
How do I go ahead and solve this problem?
Basically I just need to return true or false if where my code is running is in datacenter DC1 or DC2 or DC3. My machine name contains Datacenter information.
Joshua Bloch has mentioned an interesting use case scenario for EnumSet in Item 32 of his Java Classic Effective Java . This item advises us to use EnumSet in the place of bit fields, which is part of enum int pattern. In enum int pattern, different enum constants are represented as power of 2 and later combined using bitwise operators.
So as Puce has said in his answer you can use it like :
private static final Set<DatacenterEnum> DC_DATACENTERS = EnumSet.of(DC1, DC2, DC3);
By checking which enum you are passed (in yourEnumInstance) and returning a value based on it
switch (yourEnumInstance)
{
case DC1:
case DC2:
case DC3:
return true;
case DEV:
default:
return false;
}
It's not really clear what you want to do with all these static methods in the Enum, but regarding the asked issue, have a look at EnumSet and its contains method.
E.g.:
private static final Set<DatacenterEnum> DC_DATACENTERS = EnumSet.of(DC1, DC2, DC3);
public static boolean isDcDatacenter(DatacenterEnum datacenter){
return DC_DATACENTERS.contains(datacenter);
}
...
if (DatacenterEnum.isDcDatacenter(someDatacenter)){
...
}
String machineName = "tps1143.dc1.host.com"; // example
DatacenterEnum.valueOf(machineName.split("\\.")[1].toUpperCase()) != DataCenterEnum.DEV