Thursday, October 6, 2016

java tips


Named loops:

  1. outer:
  2. for (i = 0; i < arr.length; i++) {
  3. for (j = 0; j < arr[i].length; j++) {
  4. if (someCondition(i, j)) {
  5. break outer;
  6. }
  7. }
  8. }


Class definitions can go anywhere:

  1. class Test {
  2. public static void main(String[] args) {
  3. class Inner {
  4. void wut() {
  5. System.out.println("wut");
  6. }
  7. }
  8. new Inner().wut();
  9. }
  10. }


There is an Object called Void

Void (Java Platform SE 7 ) - (Common use case is for generic methods which need not return a value)

Double bracing Lists allows you to declare and initialize without Arrays.asList()

  1. List<String> places = new ArrayList<String>() {
  2. { add("x"); add("y"); }
  3. };


Static methods can be generic

  1. class Test {
  2.  
  3. static <T> T identity(T t) {
  4. return t;
  5. }
  6.  
  7. public static void main(String[] args) {
  8. String s = Test.<String> identity("Hi");
  9. System.out.print(s);
  10. }
  11. }


You can supply variable length params

void example(String...strings) {};

Joint-union in generic type params

public class Baz<T extends Foo & Bar> {}

Define, instantiate, and call all at once

  1. new Object() {
  2. void hi(String in) {
  3. System.out.println(in);
  4. }
  5. }.hi("weird");

No comments:

Post a Comment