Java

  1. A method's declaration tells the computer what happens if you call the method into action.
  2. if you give a method the name main, that method is called into action automatically.
  3. a statement is a direct instruction that tells the computer to do something.
  4. /** this is a javadoc comment */; you can't nest comments inside one another. Better off using end-of-line(//) comments as tools for experimenting with your code.
  5. variables vs literals: literals do not change.
  6. For most programs, just use double.
  7. Most languages use ASCII, Java uses Unicode.
  8. Any part of a Java program that has a value is an expression.
  9. System.out.println() tells the program to display a line break.
  10. Every Java class is a reference type.
  11. ClassName variableName;: a variable variableName refers to an instance of class ClassName.
  12. import static java.lang.System.out;  // out.println("blablabla");
  13. java.util.Scanner 类:
    import java.uitl.Scanner;
    // ...
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    String b = sc.next();
    // nextDouble(); nextBoolean(); ...
  14. javax.swing下的JOptionPane:
    1 import javax.swing.JOptionPane;
    2 //...
    3 String username = JOptionPane.showInputDialog("Username:");
    4 String password = JOptionPane.showInputDialog("Password");
    5 // int num1 = Integer.parseInt(JOptionPane.showInputDialog("How many cows?"));
    6 // double num2 = Double.parseDouble(JOptionPane.showInputDialog("doble?"));
  15. In java7, you can use a string as a case of switch statement. But in java 6 you cannot.
  16. sc.findWithinHorizon(".", 0).charAt(0); 获取字符串首个字符
  17. File evidence = new File("cookedBooks.txt"); evidence.delete(); // make a File object; java.io.File, delete it.
  18. Location: /System/Library/Frameworks/JavaVM.framework/Commands
  19. java.util.Random: http://www.cs.geneseo.edu/~baldwin/reference/random.html
  20. A child class can't directly reference the private fields of its parent class
  21. @Override annotation tells java compiler to lookout for a common coding error:
    public class PartTimeWithOver extends PartTimeEmployee {
    
        @Override
        public double findPaymentAmount(int hours) {
                // some code
        }
    }

    The annotation says “make sure that the method immediately following this annotation has the same stuff (the same name, the same parameters, and so on) as one of the methods in the super- class. If not, then display an error message.” 

    @Override can watch out for an overriden method, and, from Java 6 onward, you can also use @Override to signal an interface method’s implementation 

  22. Order of setting up a frame:
    • Add things to the frame
    • pack();
    • setVisible(true)
  23. Classes need to learn:
    • java.text.DecimalFormat (its not thread safe, never share decimal format between multiple threads)
    • java.lang.System.out
  24. The DecimalFormat is a subclass of NumberFormat, for programs that involve money, I use NumberFormat
    private static NumberFormat currency = NumberFormat.getCurrencyInstance(); // factory method, returns an object
    out.print(currency.format(rate));
  25. main(String args[]): command line arguments are actually strings
  26. In Java, there are two kind of exceptions,
    • checked and unchecked:
      • The potential throwing of a checked exception must be acknowledged in the code
      • The potential throwing of an unchecked exception doesn't need to be acknowledged in the code
    • Acknowledging an checked exception in the code means one of two things:
      • he statements (including method calls) that can throw the exception are inside a try clause. That try clause has a catch clause with a matching exception type in its parameter list
      • The statements(including mehtod calls) that can throw the exception are inside a method that has a throws clause in its header. The throws clause contains a matching exception type
    • Anything that’s a subclass of RuntimeException (or a sub-subclass, sub-sub-subclass, and so on) is unchecked. Any exception that’s not a descendent of RuntimeException is checked

  27. try-with-resource(java 7):
    private static void customBufferStreamCopy(File source, File target) {
        try (InputStream fis = new FileInputStream(source);
            OutputStream fos = new FileOutputStream(target)){
            byte[] buf = new byte[8192]; 
            int i;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        }
    
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    closable resource will be automatically closed in the try paranthesis

  28. In java, the default access for a member of a class is package-wide access, while protected member not only can be accessed in the same package, but also can be accessed from subclasses. A protected member is available to subclasses outside the package, but the member is also available to code (subclasses or not) within the member’s package. 
  29. public classes can be referenced from every where in your code, while non-public classes can only assecced in that class's package.
  30. In command line use:
    $ appletviewer [+ xxx.html]

    to view java applet

  31. Checked and Unchecked exception, check this out: http://www.javapractices.com/topic/TopicAction.do?Id=129
  32. Apache commons: Useful Java library: http://commons.apache.org/
  33. Eclipse shortcut:
    1. Generate Element Comment: Option+Command+j
    2. Import Organization:             Shift+Command+o
    3. Source:                                Option+Command+s
    4. Refactor:                              Option+Command+t
  34. javadoc: To generate HTML formatted documentation, run the javadoc command-line tool on your source files to generate the HTML API files (including indexes):
    javadoc -d /path/to/output /path/to/*.java

    http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

  35. In case you didn't know the default java class path includes.  If you place jars here they will be found by default:
    /Library/Java/Extensions
  36. Default CLASSPATH: The default value of the class path is ".", meaning that only the current directory is searched.
  37. The classpath is the connection between the Java runtime and the filesystem. It defines where the interpreter looks for .class files to load. The basic idea is that the filesystem hierarchy mirrors the Java package hierarchy, and the classpath specifies which directories in the filesystem serve as roots for the Java package hierarchy: http://www.ibm.com/developerworks/library/j-classpath-unix/
  38. compile to specific place:
    $ javac -d bin src/com/wei/math/Fraction.java
    // we are in Project folder
    // Project has src and bin folder
  39. ORDER:
    public class MTest extends D2{
        public static void main(String[] args) {
            MTest mt = new MTest();
        }
        
        private static int m = pt("MTest static");
        private int ii = pt("before MTest constructor");
    }
    
    class Root {
        
        public Root() {
            System.out.println("Root ");
        }
        private static int i = pt("Root static");
        private int ii = pt("before Root constructor");
    
        static int pt(String s) {
            System.out.println(s);
            return 47;
        }
    }
    
    class D1 extends Root {
        
        public D1() {
            System.out.println("D1 ");
        }
        private static int i = pt("D1 static");
        private int ii = pt("before D1 constructor");
    }
    
    class D2 extends D1 {
        public D2() {
            System.out.println("D2 ");
        }
        private static int j = pt("D2 static");
        private int ii = pt("before D2 constructor");
    } ///:~
    /** Output
    Root static
    D1 static
    D2 static
    MTest static
    before Root constructor
    Root 
    before D1 constructor
    D1 
    before D2 constructor
    D2 
    before MTest constructor */
  40. Scanner and Readable: http://lihaozy.blog.51cto.com/1112871/285597
  41. How to sort a Map:
    // version 1:
    SortedSet<String> keys = new TreeSet<String>(map.keySet());
    for (String key : keys) { 
       String value = map.get(key);
       // do something
    }
    
    // version 2:
    String[] keys = map.keySet().toArray(new String[0]);
    Arrays.sort(keys);
    Map<String,String> map2 = new LinkedHashMap<String,String>();
    for(String key : keys) {
        map2.put(key, m1.get(key));
        System.out.println(m2);
    }

    // version 3
    List sortedKeys = newArrayList(yourMap.keySet());
    Collections.sort(sortedKeys);
      
  42. Collections & Collection:
    • Interface Collection: Collection is the most basic interface for all collections in Java
    • Class Collections: Collections is a utility class providing useful static methods to use on Collection objects.
  43. How to use toArray():
     String[] y = x.toArray(new String[0]);

    x is a collection that contains only string

  44. Arrays.asList: List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
  45. Sort string of keys, case insensitive: Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
  46. An example of writing an iterator:
    import java.util.*;
    
    class PetSequence {
        protected Pet[] pets = Pets.createArray(8); // create 8 pets
    }
    
    public class NonCollectionSequence extends PetSequence {
        public Iterator<Pet> iterator() {
            return new Iterator<Pet>() {
                private int index = 0;
                public boolean hasNext() {
                    return index < pets.length;
                }
                public Pet next() { return Pets[next++]; }
                public void remove() {
                    // not implemented
                    throw new UnsupportedOperationException();
                }
            }
        }
    }
  47. Format specifier: %[argument_index$][flags][width][precision]conversion
  48. Covariance & Contravariance:
    public class Test {
    
        public class A {}
    
        public class B extends A {}
    
        public class C extends B {}
    
        public void testCoVariance(List<? extends B> myBlist) {
            B b = new B();
            C c = new C();
            myBlist.add(b); // does not compile
            myBlist.add(c); // does not compile
            A a = myBlist.get(0); 
        }
    
        public void testContraVariance(List<? super B> myBlist) {
            B b = new B();
            C c = new C();
            myBlist.add(b);
            myBlist.add(c);
            A a = myBlist.get(0); // does not compile
        }
    }
  49. Usually, classes which are collection-like can accept subclasses, and classes which are comparator-like can accept superclasses
  50. implementing java.lang.Comparable interface:
    class Person implements Comparable {
      private String firstName;
      private String lastName;
      private int age;
    
      public String getFirstName() { return firstName; }
      public void setFirstName(String firstName) { this.firstName = firstName; }
    
      public String getLastName() { return lastName; }
      public void setLastName(String lastName) { this.lastName = lastName; }
    
      public int getAge() { return age; }
      public void setAge(int age) { this.age = age; }
    
      public int compareTo(Object anotherPerson) throws ClassCastException {
        if (!(anotherPerson instanceof Person))
          throw new ClassCastException("A Person object expected.");
        int anotherPersonAge = ((Person) anotherPerson).getAge();  
        return this.age - anotherPersonAge;    
      }
      public static Comparator FirstNameComparator = new Comparator() {   // anonymous class comparator
        public int compare(Object person, Object anotherPerson) {
          String lastName1 = ((Person) person).getLastName().toUpperCase();
          String firstName1 = ((Person) person).getFirstName().toUpperCase();
          String lastName2 = ((Person) anotherPerson).getLastName().toUpperCase();
          String firstName2 = ((Person) anotherPerson).getFirstName().toUpperCase();
    
          if (!(firstName1.equals(firstName2)))
            return firstName1.compareTo(firstName2);
          else
            return lastName1.compareTo(lastName2);
        }
      };
    }

     

    import java.util.Arrays;
    import java.util.ArrayList;
    
    public class Testing {
    
      public static void main(String[] args) {
        Person[] persons = new Person[4];
        persons[0] = new Person();
        persons[0].setFirstName("Elvis");
        persons[0].setLastName("Goodyear");
        persons[0].setAge(56);
    
        persons[1] = new Person();
        persons[1].setFirstName("Stanley");
        persons[1].setLastName("Clark");
        persons[1].setAge(8);
    
        persons[2] = new Person();
        persons[2].setFirstName("Jane");
        persons[2].setLastName("Graff");
        persons[2].setAge(16);
    
        persons[3] = new Person();
        persons[3].setFirstName("Nancy");
        persons[3].setLastName("Goodyear");
        persons[3].setAge(69);
    
        System.out.println("Natural Order");
        for (int i=0; i<4; i++) {
          Person person = persons[i];
          String lastName = person.getLastName();
          String firstName = person.getFirstName();
          int age = person.getAge();
          System.out.println(lastName + ", " + firstName + ". Age:" + age);
        }
    
        Arrays.sort(persons, new LastNameComparator());
        System.out.println();
        System.out.println("Sorted by last name");
    
        for (int i=0; i<4; i++) {
          Person person = persons[i];
          String lastName = person.getLastName();
          String firstName = person.getFirstName();
          int age = person.getAge();
          System.out.println(lastName + ", " + firstName + ". Age:" + age);
        }
    
        Arrays.sort(persons);
        System.out.println();
        System.out.println("Sorted by age");
    
        for (int i=0; i<4; i++) {
          Person person = persons[i];
          String lastName = person.getLastName();
          String firstName = person.getFirstName();
          int age = person.getAge();
          System.out.println(lastName + ", " + firstName + ". Age:" + age);
        }
      }
    }
  51. ulp: unit in the last place or unit of least precision (ULP) is the spacing between floating-point numbers, i.e., the value the least significant digit represents if it is 1
  52. Comparable & Comparator: http://www.codeproject.com/Articles/566609/Difference-between-Comparator-and-Comparable-in-Ja
  53. final argument: This declares that the variable passed in cannot be reassigned:
    void foo( final String bar ) {
      bar = something; // wrong!
    }
  54. Difference between == and equals() method:
    • ==: 
      • meaning it checks to see if both objects reference the same place in memory
    • equals: 
      • by default, equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.
  55. n
  56. n
  57. n
  58. n
  59. n
  60. n
  61. n
  62. n
  63. n
  64. n
  65. n
posted @ 2013-05-01 10:27  wxwcase  阅读(210)  评论(0编辑  收藏  举报