I'm trying to both remove the method from the method ArrayList and check to see if the ArrayList is empty in one lookup.
This uses two look ups.
private Map<String, List<Method>> events;
public void removeEvent(String eventName, Method method){
try{
events.get(eventName).remove(method);
if(events.get(eventName).size() == 0){
events.remove(eventName);
}
}
catch (Exception e){
}
}
As you can see it looks up the ArrayList of methods to remove a method then looks it up again to see if its length is zero then looks it up again to remove the HashMap entry. Is their a way to combine at least the first two look ups?
You may change it to this way:
List<Method> methods = events.get(eventName);
if (methods == null) {
return;
}
methods.remove(method);
if (methods.isEmpty()) {
events.remove(eventName);
}
Below code might be helpful in your case.
It does not require to lookup second times to check the size of list.
public void removeEvent(String eventName, Method method){
try{
List<Method> methods = events.get(eventName);
methods.remove(method);
if(methods.size() == 0){
events.remove(eventName);
}
}
catch (Exception e){
}
}
Related
I am trying to serialize a Trie in Java (prefix tree),
so I wrote this code
public void serialize(DictNode node, ObjectOutputStream outPut){
if (node == null) {
return;
}
int i;
if(node==root){
try{
System.out.println(node+" root");
outPut.writeObject(node);
}catch(IOException ex) {
ex.printStackTrace();
}
}
for(i=0;i<26;i++){
if(node.array[i]!=null){
System.out.println(node.array[i]+" ser "+(char)(i+'a'));
try{
outPut.writeObject(node.array[i]);
}catch(IOException ex) {
ex.printStackTrace();
}
serialize(node.array[i],outPut/*,temp*/);
}
}
}
But it doesn't seem to work properly. So here is the thing. When I wrote a System.out.println in order to print the adresses of the nodes that I pass througth in the code that I wrote to priint the leafs. But when I do the same thing in the method of serialization the adresses are completely different even thought the code is the same. Why does this happen????
public void printLeafNodes(DictNode node,String preflix) {
if (node == null) {
return;
}
int i;
if(node.isTerminalNode){
System.out.println(preflix);
}
for(i=0;i<26;i++){
if(node.array[i]!=null){
System.out.println(node.array[i]+" "+(char)(i+'a'));
Character.toString((char)(i+'a'));
preflix=preflix+(char)(i+'a');
printLeafNodes(node.array[i],preflix);
preflix=preflix.substring(0,preflix.length()-1);
}
}
}
You print the adress of an Object (DictNode) which is different every time you serialize/desirialize, because java has to create new instances.
If you would add a toString() Method to class DictNode you will see that the content of the class is what you expect to see.
In toString() you can create a String which contains all class field informations like
"name=Hans,lastname=Wurst,age=12"
Check:
Java toString() method
How to use the toString method in
Java?
I have a simple enum that I am iterating through to check if it contains a specific value. Here is my code -
private static boolean checkCountryCode(CountryCode countryCode) {
return Arrays.asList(CountryCodeList.values()).contains(countryCode.name());
}
This always returns false although the country code I am passing in the request is present in the list. In this case, I can't override equals since its a enum.
The countryCode in the method argument has the countryCode I am passing in the request. In my case, it is UA (Ukraine). The CountryCodeList is a list pre-populated with all the country codes in which our application runs. Some of them are on this page - http://countrycode.org/
Also, please note both CountryCode, and CountryCodeList are enums.
If CountryCodeList is enum, you can refactor you code to this
private static boolean checkCountryCode(CountryCode countryCode) {
try{
return CountryCodeList.valueOf(countryCode.name()) != null;
} catch (java.lang.IllegalArgumentException e) {
return false;
}
}
I am new to Java,
Here is my code,
if( a.name == b.name
&& a.displayname == b.displayname
&& a.linkname == b.linkname
......... )
return true;
else
return false;
I will call this method and have to check that all properties of objects 'a' and 'b'.
Each object will have more than 20 properties. So, it is will be tidy if i use if case for each property.
An exception is throwed if the return is false and I have to report which property fails.
Is there any easy method to find where the condition fails within the if case.
Pls help. Ask if you are not clear about the question.
The question is, would you like to continue checking if one of the conditions fails?
You could do something like comparator where you have interface:
public interface IComparator {
boolean compare(YourObject o1, YourObject o2);
String getComparatorName();
}
Next you create set of implementations of that interface:
NameComparator implements IComparator {
private name="Name Comparator";
#Override
public boolean compare(YourObject o1, YourObjecto2) {
return o1.getName().equals(o2.getName());
}
#Override
public String getComparatorName() {
return name;
}
}
Next you store set of these comparators in arrayList and you iterate through them and record which one fails by adding them to some other collection.. Hope that helps!
For instance you create array:
IComparator[] comparators = new IComparator[]{ new NameComparator, new DisplayNameComparator};
List<IComparator> failedComparationOperations = new ArrayList<IComparator>();
for(IComparator currentComparator : comparators) {
if(!currentComparator.compare(o1, o2)) {
failedComparationOperations.add(currentComparator);
}
}
for(IComparator currentComparator: failedComparationOperations)
{
System.out.println("Failed Comparation at: "+currentComparator.getComparatorName());
}
You may use reflection: browse what fields are defined, and check each of them using method equals. Print error message if they're not equal, give summary at the end.
boolean equals = true;
Field[] fields = a.getClass().getDeclaredFields();
for (Field f: fields){
f.setAccessible(true);
try {
if (!f.get(a).equals(f.get(b))){
System.out.println(f.getName() + ": " + f.get(a) + "!="+ f.get(b));
equals = false;
};
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("equals?: " + equals);
If you need to know which of the conditions has failed you should check each of the conditions independently.
It might be a little overkill if you are dealing with this single requirement, but what about the Strategy Design Pattern?
http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
It should be an interesting option if you have other business rules that you can combine with this check.
If a and b are instances of the same class, let's assume A, and the fields are visible, then you can use reflections:
for (Field f : A.class.getFields()) {
try {
if (!f.get(a).equals(f.get(b))) {
throw new RuntimeException("Field " + f.getName() + " is different.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Without reflection you can't get maximum conciseness, but the followincg can help you to some extent. Make this kind of class:
class NamedEquals {
final String name;
final Object left, right;
NamedCondition(String name, Object left, Object right) { ...assign them... }
boolean areEqual() { return left.equals(right); }
}
Then make a List<NamedEquals>:
List<NamedEquals> conds = Arrays.asList(
new NamedEquals("name", left.name, right.name),
new NamedEquals("displayname", left. displayname, right.displayname),
...
);
And you can find if some of them fail:
for (NamedEquals eq : conds)
if (!eq.areEqual()) throw new ValidationException(eq.name);
Using a factory method can shorten the construction code:
static NamedEquals eq(String name, Object left, Object right) {
return new NamedEquals(name, left, right);
}
With that you can have
List<NamedEquals> conds = Arrays.asList(
eq("name", left.name, right.name),
eq("displayname", left. displayname, right.displayname),
...
);
How about?
// Adapted from your example:
if(!equalTo(a.name, b.name))
fail("name");
if(!equalTo(a.displayname, b.displayname))
fail("displayname");
... etc ...
...
// Allow for null values.
public boolean equalTo(Object a, Object b) {
return a != null ? a.equals(b) : b == null;
}
public void fail(String which) throws SomeException {
throw new SomeException("Failed on '"+which+"'!");
}
Another possible might be to turn each object into a Map<String,?>, perhaps by adding a Map<String,?> toMap() method to the value object, and implementing this by constructing a new map and dumping the value's fields into it. Then you can get the maps and do equals() on them.
I'm currently adding values to a HashMap<String, SpriteSheetAnimation>. I am also adding to the hashmap in the LoadFile method of my input class. When I add to the hashmap, which is part of the class GameObject that a reference is created for in the FileLoader. I alter the hashmap, adding keys and values to it, and everything is okay.
I then proceed to add the GameObject object to an objectManager where I store all of the objects for my game. When I reference the object in the ArrayList, however, the SpriteSheetAnimation value and the key of that value that I added in the file loader are no longer present. If I try to access them from within the FileLoader after adding them they are there though. I am a little confused. Is there possibly a scope issue going on here?
I've just realized something that may help you help me..(the System.out.println)
If I run this the component is not there when i try to fetch with the .toString
private void LoadControllableEntity(XMLEventReader eventReader, int x, int y)
{
entities.ControllableEntity entity = new entities.ControllableEntity(x, y);
entity.addComponent(new components.InputComponent(entity), "input");
while(eventReader.hasNext())
{
try
{
XMLEvent event = eventReader.nextEvent();
if(event.isEndElement())
{
if(event.asEndElement().getName().getLocalPart().equals("ControllableEntity"))
{
break;
}
} else if(event.isStartElement())
{
String element = (String) event.asStartElement().getName().getLocalPart();
if(element.equals("renderable"))
{
entity.addComponent(new components.Renderable(entity), "renderer");
}
else if(element.equals("animationComponent"))
{
entity.addComponent(getAnimationComponent(entity, event.asStartElement().getAttributes(), eventReader), "animation");
}
}
} catch(XMLStreamException e)
{
e.printStackTrace();
}
System.out.println(entity.getComponent("animation").toString());
managers.ObjectManager.getInstance().addObject(entity);
}
}
When I run this code though.. It can fetch the component fine(notice I've changed where I'm trying to get the component at.)
private void LoadControllableEntity(XMLEventReader eventReader, int x, int y)
{
entities.ControllableEntity entity = new entities.ControllableEntity(x, y);
entity.addComponent(new components.InputComponent(entity), "input");
while(eventReader.hasNext())
{
try
{
XMLEvent event = eventReader.nextEvent();
if(event.isEndElement())
{
if(event.asEndElement().getName().getLocalPart().equals("ControllableEntity"))
{
break;
}
} else if(event.isStartElement())
{
String element = (String) event.asStartElement().getName().getLocalPart();
if(element.equals("renderable"))
{
entity.addComponent(new components.Renderable(entity), "renderer");
}
else if(element.equals("animationComponent"))
{
entity.addComponent(getAnimationComponent(entity, event.asStartElement().getAttributes(), eventReader), "animation");
System.out.println(entity.getComponent("animation").toString());
}
}
} catch(XMLStreamException e)
{
e.printStackTrace();
}
managers.ObjectManager.getInstance().addObject(entity);
}
}
The problem with your first code-snippet is that you retrieve and print the animation entity on every pass through the loop — even before you add that entity — whereas in your second code-snippet you only retrieve and print it immediately after adding the entity, so obviously it doesn't have that problem.
I think you want to change this:
System.out.println(entity.getComponent("animation").toString());
managers.ObjectManager.getInstance().addObject(entity);
}
to this:
}
System.out.println(entity.getComponent("animation").toString());
managers.ObjectManager.getInstance().addObject(entity);
That is, I think you want those last few steps to be performed after the while-loop has completed, rather than doing it at the end of each iteration.
Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.
So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
No, can't change the structure. It's from a service I don't have control over.
No, I can't use Groovy and it's handy "Elvis" operator.
No, I'd prefer not to wait for Java 8 :D
I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.
You can use for:
product.getLatestVersion().getProductData().getTradeItem().getInformationProviderOfTradeItem().getGln();
optional equivalent:
Optional.ofNullable(product).map(
Product::getLatestVersion
).map(
ProductVersion::getProductData
).map(
ProductData::getTradeItem
).map(
TradeItemType::getInformationProviderOfTradeItem
).map(
PartyInRoleType::getGln
).orElse(null);
Your code behaves the same as
if(family != null &&
family.getPeople() != null &&
family.people.get(0) != null &&
family.people.get(0).getAddress() != null &&
family.people.get(0).getAddress().getPostalCode() != null) {
//My Code
}
Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.
If, in case, you are using java8 then you may use;
resolve(() -> people.get(0).getAddress().getPostalCode());
.ifPresent(System.out::println);
:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
REF: avoid null checks
The closest you can get is to take advantage of the short-cut rules in conditionals:
if(family != null && family.getPeople() != null && family.people.get(0) != null && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
By the way, catching an exception instead of testing the condition in advance is a horrible idea.
I personally prefer something similar to:
nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))
public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
try {
function.apply(supplier.get());
} catch (NullPointerException n) {
return null;
}
}
or something like
nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())
public static <T> T nullSafeGetter(Supplier<T> supplier) {
try {
return supplier.get();
} catch (NullPointerException n) {
return null;
}
}
Best part is the static methods are reusable with any function :)
You can get rid of all those null checks by utilizing the Java 8 Optional type.
The stream method - map() accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the neath.
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
We also have another option to achieve the same behavior is by utilizing a supplier function to resolve the nested path:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
How to invoke new method? Look below:
Outer obj = new Outer();
obj.setNested(new Nested());
obj.getNested().setInner(new Inner());
resolve(() -> obj.getNested().getInner().getFoo())
.ifPresent(System.out::println);
Instead of using null, you could use some version of the "null object" design pattern. For example:
public class Family {
private final PersonList people;
public Family(PersonList people) {
this.people = people;
}
public PersonList getPeople() {
if (people == null) {
return PersonList.NULL;
}
return people;
}
public boolean isNull() {
return false;
}
public static Family NULL = new Family(PersonList.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
import java.util.ArrayList;
public class PersonList extends ArrayList<Person> {
#Override
public Person get(int index) {
Person person = null;
try {
person = super.get(index);
} catch (ArrayIndexOutOfBoundsException e) {
return Person.NULL;
}
if (person == null) {
return Person.NULL;
} else {
return person;
}
}
//... more List methods go here ...
public boolean isNull() {
return false;
}
public static PersonList NULL = new PersonList() {
#Override
public boolean isNull() {
return true;
}
};
}
public class Person {
private Address address;
public Person(Address address) {
this.address = address;
}
public Address getAddress() {
if (address == null) {
return Address.NULL;
}
return address;
}
public boolean isNull() {
return false;
}
public static Person NULL = new Person(Address.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
etc etc etc
Then your if statement can become:
if (!family.getPeople().get(0).getAddress().getPostalCode.isNull()) {...}
It's suboptimal since:
You're stuck making NULL objects for every class,
It's hard to make these objects generic, so you're stuck making a null-object version of each List, Map, etc that you want to use, and
There are potentially some funny issues with subclassing and which NULL to use.
But if you really hate your == nulls, this is a way out.
Although this post is almost five years old, I might have another solution to the age old question of how to handle NullPointerExceptions.
In a nutshell:
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
}
Since there is a lot of legacy code still in use, using Java 8 and Optional isn't always an option.
Whenever there are deeply nested classes involved (JAXB, SOAP, JSON, you name it...) and Law of Demeter isn't applied, you basically have to check everything and see if there are possible NPEs lurking around.
My proposed solution strives for readibility and shouldn't be used if there aren't at least 3 or more nested classes involved (when I say nested, I don't mean Nested classes in the formal context). Since code is read more than it is written, a quick glance to the left part of the code will make its meaning more clear than using deeply nested if-else statements.
If you need the else part, you can use this pattern:
boolean prematureEnd = true;
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
prematureEnd = false;
}
if(prematureEnd) {
System.out.println("The else part");
}
Certain IDEs will break this formatting, unless you instruct them not to (see this question).
Your conditionals must be inverted - you tell the code when it should break, not when it should continue.
One more thing - your code is still prone to breakage. You must use if(family.getPeople() != null && !family.getPeople().isEmpty()) as the first line in your code, otherwise an empty list will throw a NPE.
If you can use groovy for mapping it will clean up the syntax and codes looks cleaner. As Groovy co-exist with java you can leverage groovy for doing the mapping.
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
instead you can do this
if(family?.people?[0]?.address?.postalCode) {
//do something
}
or if you need to map it to other object
somobject.zip = family?.people?[0]?.address?.postalCode
Not such a cool idea, but how about catching the exception:
try
{
PostalCode pc = people.get(0).getAddress().getPostalCode();
}
catch(NullPointerException ex)
{
System.out.println("Gotcha");
}
If it is rare you could ignore the null checks and rely on NullPointerException. "Rare" due to possible performance problem (depends, usually will fill in stack trace which can be expensive).
Other than that 1) a specific helper method that checks for null to clean up that code or 2) Make generic approach using reflection and a string like:
checkNonNull(family, "people[0].address.postalcode")
Implementation left as an exercise.
I was just looking for the same thing (my context: a bunch of automatically created JAXB classes, and somehow I have these long daisy-chains of .getFoo().getBar().... Invariably, once in a while one of the calls in the middle return null, causing NPE.
Something I started fiddling with a while back is based on reflection. I'm sure we can make this prettier and more efficient (caching the reflection, for one thing, and also defining "magic" methods such as ._all to automatically iterate on all the elements of a collection, if some method in the middle returns a collection). Not pretty, but perhaps somebody could tell us if there is already something better out there:
/**
* Using {#link java.lang.reflect.Method}, apply the given methods (in daisy-chain fashion)
* to the array of Objects x.
*
* <p>For example, imagine that you'd like to express:
*
* <pre><code>
* Fubar[] out = new Fubar[x.length];
* for (int i=0; {#code i<x.length}; i++) {
* out[i] = x[i].getFoo().getBar().getFubar();
* }
* </code></pre>
*
* Unfortunately, the correct code that checks for nulls at every level of the
* daisy-chain becomes a bit convoluted.
*
* <p>So instead, this method does it all (checks included) in one call:
* <pre><code>
* Fubar[] out = apply(new Fubar[0], x, "getFoo", "getBar", "getFubar");
* </code></pre>
*
* <p>The cost, of course, is that it uses Reflection, which is slower than
* direct calls to the methods.
* #param type the type of the expected result
* #param x the array of Objects
* #param methods the methods to apply
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T[] apply(T[] type, Object[] x, String...methods) {
int n = x.length;
try {
for (String methodName : methods) {
Object[] out = new Object[n];
for (int i=0; i<n; i++) {
Object o = x[i];
if (o != null) {
Method method = o.getClass().getMethod(methodName);
Object sub = method.invoke(o);
out[i] = sub;
}
}
x = out;
}
T[] result = (T[])Array.newInstance(type.getClass().getComponentType(), n);
for (int i=0; i<n; i++) {
result[i] = (T)x[i];
}
return result;
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
and my favorite, the simple try/catch, to avoid nested null checks...
try {
if(order.getFulfillmentGroups().get(0).getAddress().getPostalCode() != null) {
// your code
}
} catch(NullPointerException|IndexOutOfBoundsException e) {}