Java - Tips

From XennisWiki
Jump to: navigation, search

This article contains tips and code snippets for Java.

Basic

Timer (and TimerTask)

import java.util.Timer;
import java.util.TimerTask;
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
			
	@Override
	public void run() {
		// Do stuff here
	}
}, DELAY-IN-MILLISECONDS);

With

public interface Source<T> {
    T get();
}
public Response addCar( final String apiKey ) {

    return withValidApiKey( apiKey, () -> {
        // Do action here
        return Response.ok().build();
    } );
}

private Response withValidApiKey( final String apiKey, final Source<Response> action ) {
    if ( Strings.isBlank( apiKey ) ) {
        return Response.status( Response.Status.FORBIDDEN ).build();
    }
    return action.get();
}

hashCode and equals method

public class MyObject {

    private final Integer _type;
    private final String _value;

    // ...

    @Override
    public int hashCode() {
        return Objects.hash( _type, _value );
    }

    @Override
    public boolean equals( final Object obj ) {
        if ( obj == null ) {
            return false;
        }
        if ( obj == this ) {
            return true;
        }
        if ( obj.getClass() != this.getClass() ) {
            return false;
        }
        final MyObject cast = (MyObject) obj;
        return cast.getType().equals( _type ) && cast.getValue().equals( _value );
    }

    public String getValue() {
        return _value;
    }

    public Integer getType() {
        return _type;
    }
}

Lambda function as return method

import java.util.function.Function;

public static Function<String, String> prefixValue(int value) {
    return string -> String.format("%s %d", string, value);
}

prefixValue(42).apply("fuu");

Advanced

Observer

A short example of how to use observers in Java.

public class Car extends Observable {

        private int fillLevel = 0;

	public void refill(int i) {
                this.fillLevel += i;
		this.setChanged();
		notifyObservers(this.fillLevel);
	}
}
public class Garage implements Observer {

	@Override
	public void update(Observable observable, Object data) {
                int carFillLevel = (int) data;
                System.out.println(carFillLevel);
	}
}
public class Main {

        public static void main(String[] args) {
                Car myCar = new Car();
                Garage myGarage = new Garage();
                myCar.addObserver(myCar);

                myCar.refill(10);
        }
}

See also