How to pass different enums as argument? - java

I have some enums, all different, and I want to create a function that can find or not if a string is one of enum variable name (not sure it's really understandable).
enum MYENUM {
ONE,
TWO;
}
enum MYENUM1 {
RED,
GREEN;
}
I want to do this (this is just for the example, my enum are more complicated):
if(isInEnum(MYENUM, "one")) ...
if(isInEnum(MYENUM1, "one")) ...
isinEnum function (the code is bad, it's just for understanding):
boolean isinEnum(enum enumeration, String search) {
for(enum en : enumeration.values()){
if(en.name().equalsIgnoreCase(search)) return true;
}
return false;
}
Is this kind of thing possible?
I think not, according to what I can read on the web, but maybe someone has a solution to do this, instead of making one loop for each enum.

Here is a way using reflection...
public class EnumFinder {
public static <T extends Enum<T>> boolean isInEnum(Class<T> clazz, String name) {
for (T e : clazz.getEnumConstants()) {
if (e.name().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public static void main(String[] argv) {
System.out.println(isInEnum(MYENUM.class, "one")); // true
System.out.println(isInEnum(MYENUM1.class, "one")); // false
}
}
Your attempt in your answer was actually very close. The only difference is that Java needs an instance of the defining class in order to answers questions about an unknown type dynamically at runtime.

This may not be the cleanest solution because it uses exceptions in the normal program flow, but it is certainly short, because it avoids the loop:
boolean isinEnum(Class<T> enumClass, String search) {
try {
Enum.valueOf(enumClass, search);
return true;
} catch (IllegalArgumentException iae) {
return false;
}
}

Your question is a bit tough to understand, but I think I get the gist of it.
You might be making things a lot tougher on yourself than necessary.
Take a look at Java's map interface / data structure (in java.util) and see if that moves you closer to your solution:
java.util Interface Map<K,V>
If not, repost with any leg-work you've done and I'll see if I can help ya' further. ;-)

Related

Java 10 ifPresentOrElse that return boolean

I am a little confused on "how to do this properly":
// return true: if present and number of lines != 0
boolean isValid(Optional<File> optFile) {
return optFile.ifPresentOrElse(f -> return !isZeroLine(f), return false);
}
private boolean isZeroLine(File f) {
return MyFileUtils.getNbLinesByFile(f) == 0;
}
I know the syntax is not correct and not compiling, but it's just for you to get the idea.
How can I turn this into 'clean code'?
i.e. avoid doing:
if (optFile.isPresent()) {//} else {//}
Dealing with boolean return type(easily inferred Predicates), one way to do that could be to use Optional.filter :
boolean isValid(Optional<File> optFile) {
return optFile.filter(this::isZeroLine).isPresent();
}
But, then using Optionals arguments seems to be a poor practice. As suggested in comments by Carlos as well, another way of implementing it could possibly be:
boolean isValid(File optFile) {
return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
On another note, ifPresentOrElse is a construct to be used while performing some actions corresponding to the presence of the Optional value something like :
optFile.ifPresentOrElse(this::doWork, this::doNothing)
where the corresponding actions could be -
private void doWork(File f){
// do some work with the file
}
private void doNothing() {
// do some other actions
}

Can I use the Conditional Operators in a non-assignment situation in JAVA?

In case of assignment the situation is simple,
result = testCondition ? value1 : value2;
But what if I want to use it instead of an if statement?
for instance in a logging situation:
logger.shouldDebbug ? logger.log("logging") : (what to do if not?);
In the case I don't what to do anything in the case of false, can I still use this Operator?
Yes you can if you wrap them in a returning function, but no you shouldn't.
In your example of the logger, let your logger output to void, discard the input when debugging isn't enabled.
You do not want to riddle your code with all these logging checks.
Perform a check as least and as central as possible.
Either have a check in the logger.log function if debugging is enabled, or replace the logger with a dummy mock that does nothing except accept input and immediately discard it.
If you use standard logging frameworks like log4j you can set debugging levels, where you show only info or more serious, only warnings or more serious, only errors or more serious.
The same goes for other "quick" checks. If you find yourself using a certain pattern a lot, write a utility class for it with a static method if need be, so you have one place, where you have to change stuff, instead of 200 code points that you have to update when going to production.
You could use it if you insist, by defining a meaningless variable and take advantage of the functions' side-effects, but that's not a very good coding habit. It's purely a work-around.
For example:
public static boolean test() {
return 1>0;
}
public static int success() {
System.out.println("true");
return 0; // has no meaning whatsoever
}
public static int fail() {
System.out.println("false");
return 0; // has no meaning whatsoever
}
public static void main(String[] args) {
int meaningless = test() ? success() : fail();
}
Everything has been explained in comments, so I will put here only some idea:
public class Ternary {
private final boolean condition;
private Ternary(boolean condition) { this.condition = condition; }
public static Ternary of(boolean condition) { return new Ternary(condition); }
public Ternary onTrue(Runnable r) { if (condition) { r.run(); } return this; }
public Ternary onFalse(Runnable r) { if (!condition) { r.run(); } return this; }
}
Example of usage:
Ternary.of(o != null).onTrue(() -> doSomething()).onFalse(() -> doSomethingElse());
But simplier would be to write:
if (o != null) { doSomething(); } else { doSomethingElse(); }

Assign if not null or if not set in Java

I am really tired of doing all the if null checks, resp. I also want to have a more configurable scenario for this. Let me explain this by an example:
I have a getter() which may return null or '0' in both cases the resp. setter() should not be called passing the getter().
So the implementation is
if(getter() != null && !getter().equals('0')) setter(getter());
this however really anoys me, especially if getter() and setter() are really long method calls and I have to introduce helper variables for this.
I am thinking about a method with parameter
ifNotSet(getter(), setter(), new Object[null, '0']);
which does exactly the same thing. Where the parameters to ifNotSet are
getter - the method to check if it does not equal one of the conditions
setter - the method to call in the way setter(getter) if conditions does not apply
conditions - the conditions which must not apply on evaluation of getter() for the method to be executed
At first sight this does not seem to complicated, it however is! Is anyone aware of a solution to this problem or any kind of implementation?
Thanks!
Update
I've been working some more on the problem, after the feedback of you guys, and found out about the following
private boolean ns(Object[] condition, Object getter) {
boolean ret = false;
for (Object object : condition) {
if(getter) equals or == ??
}
return true;
}
Object[] cond = new Object[] { null, "0" };
Object a;
if (ns(cond, a = getter()))setter(a);
Well, this seemed to be at least a solution if you have a lot of allocations to do. However, if you take a look at the ns() method... the question on the incoming conditions is, whether to use == or equals to do the comparison!?
You can use this way
public boolean checkNotNullOrZero(String s)
{
return (s!=null) && !s.equals("0");
}
Basic use:
if(checkNotNullOrZero(getter()))
{
setter(getter());
}
You can't do what that as in Java methods are not first-class citizens. You could use reflection or anon classes but it would be way more work .
If null and zero are always equivalent for getter then could that be changed to return just one of the two?
If null and zero are always equivalent for setter then could that be changed to normalize the two?
Could you create a method isNullOrZero(x) then you can have
if (!isNullOrZero(getter())) {
setter(getter());
}
Ugly way of doing this literally in Java:
public interface Getter {
public Object get();
}
public interface Caller {
public void call();
}
public void callIfNotNull(Getter getter, Caller caller, Object[] nullObjects) {
Object value = getter.get();
for(Object nullObject : nullObjects) {
if(value==nullObject) {
return;
}
}
caller.call();
}
Usage:
callIfNotNull(new Getter() {
#Override
public Object get() {
return getterMethod();
}
}, new Caller() {
#Override
public void call() {
setter();
}
}, new Object[]{null, '0'});
}
You might need to implement sane way to check for null objects and give reasonable names.
Personnaly, I wouldn't go with this approach. I would try to implement Null Object pattern to resolve an issue.

Reducing if-else statements in Java

I have the following code:
void f(String t)
{
if(t.equals("a"))
{
someObject.setType(ObjectType.TYPE_A);
}
else if(t.equals("b"))
{
someObject.setType(ObjectType.TYPE_B);
}
// 50 more similar code
}
Is there any simple way to rewrite the if-else condition so as not to have that much code?
You should use something to eliminate the repetition of someObject.setType(ObjectType....)) If ObjectType is an enum, then write a method there similar to valueOf that will achieve that. See if you like this kind of solution:
void f(String t) { someObject.setType(ObjectType.byName(t)); }
enum ObjectType {
TYPE_A, TYPE_B;
public static ObjectType byName(String name) {
return valueOf("TYPE_" + name.toUpperCase());
}
}
Use a Map (which you'll have to populate) that maps from String to whatever type your ObjectType.TYPE_x values are.
I would add this as a functionality of the enum:
public enum ObjectType {
TYPE_A("a"),
TYPE_B("b");
private String stringType;
private ObjectType(String stringType) {
this.stringType = stringType;
}
public String getStringType() {
return this.stringType;
}
public static ObjectType fromStringType(String s) {
for (ObjectType type : ObjectType.values()) {
if (type.stringType.equals(s)) {
return type;
}
}
throw new IllegalArgumentException("No ObjectType with stringType " + s);
}
}
...
void f(String t) {
someObject.setType(ObjectType.fromStringType(t));
}
If you can refactor t into a char, you could use switch instead (Java 6):
void f(char t) {
switch(t) {
case 'a`:
someObject.setType(ObjectType.TYPE_A);
break;
case 'b':
someObject.setType(ObjectType.TYPE_B);
break;
// ...
}
}
As Marko pointed out, you could go with String too in Java 7.
It isn't that much shorter, but more elegant. Moreover, I think it might be faster too, as switch works close to O(1) with jump tables (Can somebody confirm whether this is true?), whether a number of if statements is O(n).
Fore more complex implementations than just a single setType you might think of a State Pattern implementation too.
1.You can go for Switch statement if you have number of if conditions more than 3.
2.you can convert your if else statements to ternary operations
The other suggestions are great - particularly smarter enums and maps. But the first most basic refactoring I would tackle here is to extract a method to return the enum directly and have the caller perform nothing more than the setType to that method's return value.
void f(String t) {
final ObjectType type = findType(t);
if (type != null)
someObject.setType(type);
}
ObjectType findType(String t) {
if (t.equals("a")) return ObjectType.TYPE_A;
if (t.equals("b")) return ObjectType.TYPE_B;
// 50 more similar code
}
In some cases this will be sufficient in and of itself; in others the findType() method may lead you to a simple map- or enum-based solution.

Java stuff you didn't know you didn't know [duplicate]

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?
Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.
ThreadLocals are typically not so widely known as a way to store per-thread state.
Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.
Joint union in type parameter variance:
public class Baz<T extends Foo & Bar> {}
For example, if you wanted to take a parameter that's both Comparable and a Collection:
public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);
}
This contrived method returns true if the two given collections are equal or if either one of them contains the given element, otherwise false. The point to notice is that you can invoke methods of both Comparable and Collection on the arguments b1 and b2.
I was surprised by instance initializers the other day. I was deleting some code-folded methods and ended up creating multiple instance initializers :
public class App {
public App(String name) { System.out.println(name + "'s constructor called"); }
static { System.out.println("static initializer called"); }
{ System.out.println("instance initializer called"); }
static { System.out.println("static initializer2 called"); }
{ System.out.println("instance initializer2 called"); }
public static void main( String[] args ) {
new App("one");
new App("two");
}
}
Executing the main method will display:
static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called
I guess these would be useful if you had multiple constructors and needed common code
They also provide syntactic sugar for initializing your classes:
List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};
Map<String,String> codes = new HashMap<String,String>(){{
put("1","one");
put("2","two");
}};
JDK 1.6_07+ contains an app called VisualVM (bin/jvisualvm.exe) that is a nice GUI on top of many of the tools. It seems more comprehensive than JConsole.
Classpath wild cards since Java 6.
java -classpath ./lib/* so.Main
Instead of
java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main
See http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
For most people I interview for Java developer positions labeled blocks are very surprising. Here is an example:
// code goes here
getmeout:{
for (int i = 0; i < N; ++i) {
for (int j = i; j < N; ++j) {
for (int k = j; k < N; ++k) {
//do something here
break getmeout;
}
}
}
}
Who said goto in java is just a keyword? :)
How about covariant return types which have been in place since JDK 1.5? It is pretty poorly publicised, as it is an unsexy addition, but as I understand it, is absolutely necessary for generics to work.
Essentially, the compiler now allows a subclass to narrow the return type of an overridden method to be a subclass of the original method's return type. So this is allowed:
class Souper {
Collection<String> values() {
...
}
}
class ThreadSafeSortedSub extends Souper {
#Override
ConcurrentSkipListSet<String> values() {
...
}
}
You can call the subclass's values method and obtain a sorted thread safe Set of Strings without having to down cast to the ConcurrentSkipListSet.
Transfer of control in a finally block throws away any exception. The following code does not throw RuntimeException -- it is lost.
public static void doSomething() {
try {
//Normally you would have code that doesn't explicitly appear
//to throw exceptions so it would be harder to see the problem.
throw new RuntimeException();
} finally {
return;
}
}
From http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html
Haven't seen anyone mention instanceof being implemented in such a way that checking for null is not necessary.
Instead of:
if( null != aObject && aObject instanceof String )
{
...
}
just use:
if( aObject instanceof String )
{
...
}
Allowing methods and constructors in enums surprised me. For example:
enum Cats {
FELIX(2), SHEEBA(3), RUFUS(7);
private int mAge;
Cats(int age) {
mAge = age;
}
public int getAge() {
return mAge;
}
}
You can even have a "constant specific class body" which allows a specific enum value to override methods.
More documentation here.
The type params for generic methods can be specified explicitly like so:
Collections.<String,Integer>emptyMap()
You can use enums to implement an interface.
public interface Room {
public Room north();
public Room south();
public Room east();
public Room west();
}
public enum Rooms implements Room {
FIRST {
public Room north() {
return SECOND;
}
},
SECOND {
public Room south() {
return FIRST;
}
}
public Room north() { return null; }
public Room south() { return null; }
public Room east() { return null; }
public Room west() { return null; }
}
EDIT: Years later....
I use this feature here
public enum AffinityStrategies implements AffinityStrategy {
https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java
By using an interface, developers can define their own strategies. Using an enum means I can define a collection (of five) built in ones.
As of Java 1.5, Java now has a much cleaner syntax for writing functions of variable arity. So, instead of just passing an array, now you can do the following
public void foo(String... bars) {
for (String bar: bars)
System.out.println(bar);
}
bars is automatically converted to array of the specified type. Not a huge win, but a win nonetheless.
My favorite: dump all thread stack traces to standard out.
windows: CTRL-Break in your java cmd/console window
unix: kill -3 PID
A couple of people have posted about instance initializers, here's a good use for it:
Map map = new HashMap() {{
put("a key", "a value");
put("another key", "another value");
}};
Is a quick way to initialize maps if you're just doing something quick and simple.
Or using it to create a quick swing frame prototype:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
panel.add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
frame.add( panel );
Of course it can be abused:
JFrame frame = new JFrame(){{
add( new JPanel(){{
add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
}});
}};
Dynamic proxies (added in 1.3) allow you to define a new type at runtime that conforms to an interface. It's come in handy a surprising number of times.
final initialization can be postponed.
It makes sure that even with a complex flow of logic return values are always set. It's too easy to miss a case and return null by accident. It doesn't make returning null impossible, just obvious that it's on purpose:
public Object getElementAt(int index) {
final Object element;
if (index == 0) {
element = "Result 1";
} else if (index == 1) {
element = "Result 2";
} else {
element = "Result 3";
}
return element;
}
I think another "overlooked" feature of java is the JVM itself. It is probably the best VM available. And it supports lots of interesting and useful languages (Jython, JRuby, Scala, Groovy). All those languages can easily and seamlessly cooperate.
If you design a new language (like in the scala-case) you immediately have all the existing libraries available and your language is therefore "useful" from the very beginning.
All those languages make use of the HotSpot optimizations. The VM is very well monitor and debuggable.
You can define an anonymous subclass and directly call a method on it even if it implements no interfaces.
new Object() {
void foo(String s) {
System.out.println(s);
}
}.foo("Hello");
The asList method in java.util.Arrays allows a nice combination of varargs, generic methods and autoboxing:
List<Integer> ints = Arrays.asList(1,2,3);
Using this keyword for accessing fields/methods of containing class from an inner class. In below, rather contrived example, we want to use sortAscending field of container class from the anonymous inner class. Using ContainerClass.this.sortAscending instead of this.sortAscending does the trick.
import java.util.Comparator;
public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
Comparator comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (sortAscending || ContainerClass.this.sortAscending) {
return o1 - o2;
} else {
return o2 - o1;
}
}
};
return comparator;
}
}
Not really a feature, but an amusing trick I discovered recently in some Web page:
class Example
{
public static void main(String[] args)
{
System.out.println("Hello World!");
http://Phi.Lho.free.fr
System.exit(0);
}
}
is a valid Java program (although it generates a warning).
If you don't see why, see Gregory's answer! ;-) Well, syntax highlighting here also gives a hint!
This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:
Class sun.misc.Unsafe - will allow you to implement direct memory management in Java (you can even write self-modifying Java code with this if you try a lot):
public class UnsafeUtil {
public static Unsafe unsafe;
private static long fieldOffset;
private static UnsafeUtil instance = new UnsafeUtil();
private Object obj;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe)f.get(null);
fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
When working in Swing I like the hidden Ctrl - Shift - F1 feature.
It dumps the component tree of the current window.
(Assuming you have not bound that keystroke to something else.)
Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode.
(Explanation)
My vote goes to java.util.concurrent with its concurrent collections and flexible executors allowing among others thread pools, scheduled tasks and coordinated tasks. The DelayQueue is my personal favorite, where elements are made available after a specified delay.
java.util.Timer and TimerTask may safely be put to rest.
Also, not exactly hidden but in a different package from the other classes related to date and time. java.util.concurrent.TimeUnit is useful when converting between nanoseconds, microseconds, milliseconds and seconds.
It reads a lot better than the usual someValue * 1000 or someValue / 1000.
Language-level assert keyword.
Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.
The addition of the for-each loop construct in 1.5. I <3 it.
// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {
System.out.println(foo.toString());
}
And can be used in nested instances:
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
Link to the Sun documentation
i personally discovered java.lang.Void very late -- improves code readability in conjunction with generics, e.g. Callable<Void>

Categories

Resources