Saturday, September 5, 2015

Java Basic Miscs



https://www.yfzzweb.com/%E9%9D%A2%E8%AF%95%E9%A2%98/java-this-override/
  1. 子类与父类之间的调用关系:动态分派 在调用new B()时调用A的构造器时和super.getValue()时的setValue(int value)方法是根据隐式对象的实际类型来确定的。只有实际类型未重写该方法时,才按照继承层次由下往上查找。这个可以参阅《深入理解JVM》的“分派”一节。
由一道 Java finally 执行顺序的题引发的思考
public class test1 {
    static String s = "A";

    public static void main(String[] args) {
        System.out.println(test());
        System.out.println(s);
    }

    private static String test() {
        try {
            System.out.println("A");
            return s = "A";
        } finally {
            System.out.println("B");
            s = "B";
        }
    }
}

执行结果是 ABAB ,
finally 语句块在 return 语句之后,return 返回之前执行

public class FinallyTest1 {

    public static void main(String[] args) {
        System.out.println(test1());
    }

    public static int test1() {
        int b = 20;

        try {
            System.out.println("try block");

            return b += 80;
        } catch (Exception e) {
            System.out.println("catch block");
        } finally {
            System.out.println("finally block");

            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }
        }

        return b;
    }

}
运行结果:
try block
finally block
b>25, b = 100
100
可以根据运行结果得知,在 finally 语句块执行之前,return b += 80; 中的 b + =80; 这部分已经运行,但是没有返回,然后等 finally 执行完以后才返回结果的
如果,finally 中对 return 返回的变量进行了修改,那么 return 返回的是修改前的值还是修改后的值?
对于基本数据类型和引用数据类型,结论是不同的,再次总结下结论吧:
  • 对于基本数据类型,finally 语句块中对 try 语句块的 return 的变量进行了修改,return 的则是修改前的值。
  • 对于引用数据类型,finally 语句块中对 try 语句块的 return 的变量进行了修改,return 的则是修改后的值。
看到这里,不知道你有没有想到这个结论与 Java 的方法调用时的所谓的 值传递 和 引用传递 的结论有些类似。
先说基本数据类型,由于基本数据类型是 值传递 ,所以在 try 里的 return 执行的时候,就先将变量的值隐性的作为最终返回的值。
同样的,对于引用数据类型,只是将该变量所指向的内存地址隐性的作为最终返回的值,所以即使将 stu = null,也无所谓了,因为早在执行 finally 之前,try里的 return 就已经拿到了 stu 所指向的地址。
这里多说一句,其实 Java 里都是值传递,只不过基本数据类型的值是真正的值,而引用数据类型是地址值而已。(如果你看这句话更晕的话,就先跳过去这句话,反正本篇文章也不是为了解释这个的。)
问:如果 try 与 finally 中都有 return 语句,那么到底会返回哪一个呢?
会返回 finally 中的 return 。

问:如果 try 里有 return 语句,整个 try-catch-finally 块之外也有一个 return语句,那么哪个会执行,一定是这样么?
在 try 里没有发生异常的情况下,是 try 里的 return 会执行,但发生了异常,则反之。

问:如果 catch 中有 return 语句呢?当然只有在异常的情况下才有可能会执行,那么是在 finally 之前就返回吗?
当发生异常后,catch 中的 return 执行情况与未发生异常时 try 中 return 的执行情况完全一样。
finally 块的语句在 try 或 catch 中的 return 语句执行之后返回之前执行,且 finally 里的修改语句可能影响也可能不影响 try 或 catch 中 return 已经确定的返回值,若 finally 里也有 return 语句则覆盖 try 或 catch 中的 return 语句直接返回。
http://www.java2s.com/Tutorials/Java/java.nio.file/Files/Java_Files_readAllLines_Path_path_Charset_cs_.htm
    Path wiki_path = Paths.get("C:/tutorial/wiki", "wiki.txt");

    List<String> lines = Files.readAllLines(wiki_path, charset);

String str = FileUtils.readFileToString(new File("test.txt"));
http://examples.javacodegeeks.com/java-basics/switch-statement/java-switch-case-example/
The syntax of a switch case statement is the following:
switch (variable) {
  case c1:
        statements // they are executed if variable == c1
        break;
  case c2: 
        statements // they are executed if variable == c2
        break;
  case c3:
  case c4:        
        statements // they are executed if variable ==  any of the above c's
        break;
  . . .
  default:
        statements // they are executed if none of the above case is satisfied
        break;
}
  • switch: the switch keyword is followed by a parenthesized expression, which is tested for equality with the following cases. There is no bound to the number of cases in aswitch statement.
  • case: the case keyword is followed by the value to be compared to and a colon. Its value is of the same data type as the variable in the switch. The case which is equal to the value of the expression is executed.
  • default: If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the "else" for the switch statement. It is conventionally written after the last case, and typically isn’t followed by break because execution just continues out of the switch. However, it would be better to use a breakkeyword to default case, too. If no case matched and there is no default clause, execution continues after the end of the switch statement.
  • break: The break statement causes execution to exit the switch statement. If there is nobreak, execution flows through into the next case, but generally, this way is not preferred.
http://javarevisited.blogspot.com/2015/05/fixing-unsupported-majorminor-version.html
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
javac -target 1.4 HelloWorld.java

Why you shouldn't use == with float and double in Java?
Avoid using double and float for monetary calculation
for(double balance = 10; balance > 0; balance-=0.1) {
   System.out.println(balance);
}
If you think little bit than you will realize that greater than will definitely end this loop, but don't expect it to print numbers like 9.99.89.7 because floating point numbers are just approximation, they are not exact. Some numbers e.g. 1/3 cannot be represented exactly using float and double in Java.
http://javarevisited.blogspot.com/2012/02/java-mistake-1-using-float-and-double.html
one should use BigDecimal for financial calculations.
  • Don’t use float and double on monetary calculation.
  • Use BigDecimal, long or int for monetary calculation.
  • Use BigDecimal with String constructor and avoid double one.
  • Don’t use floating point result for comparing loop conditions.
BigDecimal amount3 = new BigDecimal("2.15");
http://javarevisited.blogspot.com/2015/08/how-to-calculate-large-factorials-using-BigInteger-Java-Example.html
1. The BigInteger class is used to represent arbitrarily large numbers. Overflow doesn't occur as is the case with int and long primitive.

2. The BigInteger class is immutable which means that the object on which the multiply function was invoked doesn't change the integer it is holding. The multiplication is performed and a new BigInteger is returned which needs to be stored in the variable fact.
factorial = factorial.multiply(BigInteger.valueOf(i));

Java: generic enum in method parameter
public static <E extends Enum<E>> EnumSet<E> of(E e)
public class Bar<E extends Enum<E>> 
Replacing illegal character in fileName
myString = myString.replaceAll("[^a-zA-Z0-9.-]", "_");
In most regex flavors, the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\), the caret (^), and the hyphen (-). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash. To search for a star or plus, use [+*]. Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability.

String.format
log.debug( String.format("%s is %d years old, er, young", "Al", 45) );
http://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/
"% [argument index] [flag] [width] [.precision] type"
Print Integer
  • %d       : will print the integer as it is.
  • %6d    : will pint the integer as it is. If the number of digits is less than 6, the output will be padded on the left.
  • %-6d  : will pint the integer as it is. If the number of digits is less than 6, the output will be padded on the right.
  • %06d : will pint the integer as it is. If the number of digits is less than 6, the output will be padded on the left with zeroes.
  • %.2d : will print maximum 2 digits of the integer.
  • %s       : will print the string as it is.
  • %15s    : will pint the string as it is. If the string has less than 15 characters, the output will be padded on the left.
  • %-6s  : will pint the string as it is. If the string has less than 6 characters, the output will be padded on the left.
  • %.8d : will print maximum 8 characters of the string.
  • %f       : will print the number as it is.
  • %15f    : will pint the number as it is. If the number has less than 15 digits, the output will be padded on the left.
  • %.8f : will print maximum 8 decimal digits of the number.
  • %9.4f : will print maximum 4 decimal digits of the number. The output will occupy 9 characters at least. If the number of digits is not enough, it will be padded
How to Clone Collection in Java - Deep copy of ArrayList and HashSet
Programmer often mistook copy constructors provided by various collection classes, as a mean to clone Collection.

copy constructor of Collection in Java only provides shallow copy and not deep copy, which means objects stored in both original List and cloned List will be same and point to same memory location in Java heap.
in almost all cases, clone should be independent of original object.
-- This is shallow copy.
// creating copy of Collection using copy constructor
Collection<Employee> copy = new HashSet<>(org);
In order to fix this, we need to deep clone Employee object by iterating over Collection and before that, we need to override clone method for Employee object.
    protected Employee clone() {
        Employee clone = null;
        try{
            clone = (Employee) super.clone();
           
        }catch(CloneNotSupportedException e){
            throw new RuntimeException(e); // won't happen
        }
       
        return clone;
       
    }
Iterator<Employee> iterator = org.iterator();
while(iterator.hasNext()){
    copy.add(iterator.next().clone());
}

详解Java中的clone方法 -- 原型模式
在java语言中,有几种方式可以创建对象呢?

1 使用new操作符创建一个对象
2 使用clone方法复制一个对象

那么这两种方式有什么相同和不同呢? new操作符的本意是分配内存。程序执行到new操作符时, 首先去看new操作符后面的类型,因为知道了类型,才能知道要分配多大的内存空间。分配完内存之后,再调用构造函数,填充对象的各个域,这一步叫做对象的初始化,构造方法返回后,一个对象创建完毕,可以把他的引用(地址)发布到外部,在外部就可以使用这个引用操纵这个对象。

而clone在第一步是和new相似的, 都是分配内存,调用clone方法时,分配的内存和源对象(即调用clone方法的对象)相同,然后再使用原对象中对应的各个域,填充新对象的域, 填充完成之后,clone方法返回,一个新的相同的对象被创建,同样可以把这个新对象的引用发布到外部。
深拷贝 or 浅拷贝
clone是浅拷贝的

覆盖Object中的clone方法, 实现深拷贝

现在为了要在clone对象时进行深拷贝, 那么就要Clonable接口,覆盖并实现clone方法,除了调用父类中的clone方法得到新的对象, 还要将该类中的引用变量也clone出来。如果只是用Object中默认的clone方法,是浅拷贝的

Double Brace Initialization
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated.
The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors).

Don’t be “Clever”: The Double Curly Braces Anti Pattern
http://blog.takipi.com/4-out-of-5-java-developers-failed-to-solve-this-question/

http://norvig.com/java-iaq.html
You defined the wrong equals method. For example, you wrote:
public class C {
  public boolean equals(C that) { return id(this) == id(that); }
}
Q: Is null an Object?
Absolutely not. By that, I mean (null instanceof Object) is false. Some other things you should know about null:
  1. You can't call a method on null: x.m() is an error when x is null and m is a non-static method. (When m is a static method it is fine, because it is the class of x that matters; the value is ignored.)
  2. There is only one null, not one for each class. Thus, ((String) null == (Hashtable) null), for example.
Is Your Java Application Hostile to JIT Compilation?
Hotspot has a large number of different optimization techniques for JIT compilation - but one of the most important for our purposes is inlining. 

细话Java:"失效"的private修饰符
OuterClass.InnerClass inner = outer.new InnerClass();

在内部类构造的时候,会将外部类的引用传递进来,并且作为内部类的一个属性,所以内部类会持有一个其外部类的引用。
this$0就是内部类持有的外部类引用,通过构造方法传递引用并赋值。

当内部类调用外部类的私有属性时,其真正的执行是调用了编译器生成的属性的静态方法(即acess$0,access$1等)来获取这些属性值。这一切都是编译器的特殊处理。

if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

意思是 如果(内部类的)成员和构造方法设定成了私有修饰符,当且仅当其外部类访问时是允许的。

如何让内部类私有成员不被外部访问
-- 使用匿名内部类

Java的内部类构造时持有对外部类的应用,C++不会,这一点和C++不一样。

https://github.com/cxxr/better-java
Avoid Nulls
Use @Nullable, Optional.
Collections should, whenever possible, use the Guava ImmutableMap, ImmutableList, or ImmutableSet classes. These have builders so that you can build them up dynamically and then mark them immutable by calling the build method.

Classes should be made immutable by declaring fields immutable (via final) and by using immutable collections. Optionally, you can make the class itself final so that it can't be extended and made mutable.

Avoid lots of Util classes

Streams
final List<String> filtered = list.stream()
    .filter(s -> s.startsWith("s"))
    .map(s -> s.toUpperCase());

Deploying


Dependency Convergence

With the Maven dependency convergence plugin, the build will error if your dependencies don't use the same version.
Explicitly pick a version for Bar in your dependencyManagement section
Exclude Bar from either Foo or Widget

Continuous Integration
Jenkins and Travis-CI are natural choices.
Code coverage is useful, and Cobertura has a good Maven plugin and CI support.


Joda-Time
Lombok

The Checker Framework
Guava
If you're stuck with Java 6 or 7, you can use the Collections2 class, which has methods like filter and transform.

Top 10 Useful, Yet Paranoid Java Programming Techniques

1. Put the String literal first
2. Don’t trust the early JDK APIs
So be prepared and add that null check!

3. Don’t trust that “-1”
5. Check for null AND length
6. All methods are final
7. All variables and parameters are final
8. Don’t trust generics when overloading

// Bad
<T> void bad(T value) {
    bad(Collections.singletonList(value));
}
<T> void bad(List<T> values) {
    ...
}
// Good
final <T> void good(final T value) {
    if (value instanceof List)
        good((List<?>) value);
    else
        good(Collections.singletonList(value));
}
final <T> void good(final List<T> values) {
    ...
}
9. Always throw on switch default
10. Switch with curly braces

10 Subtle Best Practices when Coding Java
3. Avoid returning anonymous, local, or inner classes
The Rule: Whenever you write an anonymous, local or inner class, check if you can make it static or even a regular top-level class. Avoid returning anonymous, local or inner class instances from methods to the outside scope.

What would otherwise be a completely independent HashMap instance now keeps a reference to the outer instance, whatever that just happens to be. Besides, you’ll create an additional class for the class loader to manage.

The Rule: Whenever you implement logic using before/after, allocate/free, take/return semantics, think about whether the after/free/return operation should perform stuff in the inverse order.

5. Avoid returning null from API methods
Use null only for the “uninitialised” or “absent” semantics.

6. Never return null arrays or lists from API methods
Null does not help in finding the error
Null does not allow to distinguish I/O errors from the File instance not being a directory
Everyone will keep forgetting about null, here

8. Short-circuit equals()
10. Avoid the method(T…) signature


Annotations
http://minds.coremedia.com/2012/10/31/jsr-305-nonnull-and-guava-preconditions/
@Nonnull
Object getThat(@Nonnull Object in) {
  Preconditions.checkNotNull(in, "in must not be null.");
  ...
}
Beginning in Java SE 8, annotations can be applied to types in addition to all of their existing uses within Java declarations. This means annotations can now be applied anywhere a type is specified, including during class instance creation, type casting, the implementation of interfaces, and the specification of throws clauses. This allows developers to apply the benefits of annotations in even more places.

JSR-303
Used for runtime bean validation, NOT static code analysis
javax.validation.constraints.NotNull
javax.validation.constraints.Null


JSR-305 - dormant
Used for Static code analysis - seems to be all but dead
javax.annotation.Nonnull
javax.annotation.Nullable

Utils:
http://www.javatpoint.com/Scanner-class
public String nextLine() it moves the scanner position to the next line and returns the value as a string.
String input = "10 tea 20 coffee 30 tea buiscuits";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();


Infinite Loops. Or: Anything that Can Possibly Go Wrong, Does.

http://www.javaspecialists.eu/archive/Issue230.html
string.subString - O(n) in jdk 7,8, O(1) before

Multidimensional Array Traversal in Java
/**
 * If we switch the inner and outer loops,
     * the program will traverse the matrix in row-major order, 
     * i.e. it will sweep each row before going to a new one, 
     * which means it accesses a different column (and hence a different page) every time it accesses the array.
     * This slight change to the code caused the program to take more time to complete. 
 */
private static void rowMajor(int arr[][]) {
for(int i=0;i<ARR_SIZE;i++){
for (int j=0;j<ARR_SIZE;j++){
/*See this , we are traversing j first and then i, but to access the 
* element, more effort is involved now as they are farther located
*/
arr[j][i]=i+j;
}
}
}
A 2-D Array is really an Array of Arrays
Top 8 Diagrams for Understanding Java
The equals() and hashCode() Contract
HashCode is designed to improve performance. The contract between equals() and hasCode() is that:
1. If two objects are equal, then they must have the same hash code.
2. If two objects have the same hashcode, they may or may not be equal.
https://dzone.com/articles/constants-in-java-the-anti-pattern-1
Use final constant class - not interface
So a good design for a Constants classes would be:
//make the class non-extendable by adding final
public final class Constants {
//Hide the constructor
private Constants(){}
public static String NAME="name";
}

Java ServiceLoader
http://www.mytechnotes.biz/2013/03/java-serviceloader-example.html
http://javaevangelist.blogspot.com/2013/11/serviceloader-dynamic-reloading-on-jee7.html
    public static <T> T loadService(Class<T> api) {
        T result = null;
        ServiceLoader<T> impl = ServiceLoader.load(api);
        for (T loadedImpl : impl) {
            result = loadedImpl;
            if ( result != null ) break;
        }
        if ( result == null ) throw new RuntimeException(
            "Cannot find implementation for: " + api);
        return result; 
    }
http://codecloud.net/java-how-to-split-a-string-6200.html
String.split(regex)接受一个正则表达式作为参数,注意处理好特殊字符串,像句号、逗号。
String[] output = test.split(Pattern.quote("."));
StringTokenizer是老版本对方法,不鼓励使用,推荐使用String.split()
StringTokenizer token = new StringTokenizer(test, ".");

while (token.hasMoreTokens()) {
        System.out.println(token.nextToken());
}

if(a.replaceAll("\\s+","").equalsIgnoreCase(b.replaceAll("\\s+",""))) 
Most Popular Java Questions on Stackoverflow
Java is always pass-by-value. Unfortunately, they decided to call pointers references, thus confusing newbies. Because those references are passed by value.

int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j)?
Solution
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
There are several differences between HashMap and Hashtable in Java:
  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of NULL values.
  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.
5) (How to) Read/convert an InputStream to a String
Suppose I have an InputStream that contains text data, and I want to convert this to a String(for example, so I can write the contents of the stream to a log file).
What is the easiest way to take the InputStream and convert it to a String?
Solution
A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or even
// NB: does not close inputStream, you can use IOUtils.closeQuietly for that
String theString = IOUtils.toString(inputStream, encoding); 
Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers
6) Why is char[] preferred over String for passwords in Java?
In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords.
Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[].
Solution
Strings are immutable. That means once you've created the string, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before GC kicks in.
With an array, you can explicitly wipe the data after you're done with it: you can overwrite the array with anything you like, and the password won't be present anywhere in the system, even beforegarbage collection.
So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.

What's the best way to iterate over the items in a HashMap?
Iterate through the entrySet like so:

8) (How to) Create ArrayList from array
new ArrayList<Element>(Arrays.asList(array))

10) Generating random integers in a range with Java
public static int randInt(int min, int max) {

    Random rand;
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

What's the quickest way to remove an element from a Map by value in Java?
map.values().remove(valueToRemove);

BitSet
http://lemire.me/blog/2012/11/13/fast-sets-of-integers/
http://kinoshita.eti.br/2012/10/20/replacing-a-hashset-with-a-bitset.html
BitSet toRemove = new BitSet();
for (Map.Entry<Character, MutableInt> e : occurrences.entrySet()) {
    Character v = e.getKey();
    int found = 0;
    for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {
        found = indexOf(array, v.charValue(), found);
        if (found < 0) {
            break;
        }
        toRemove.set(found++);
    }
}
return (char[]) removeAll(array, toRemove);
The first difference is at line 1. Instead of a HashSet, it is now using a BitSet. And at line 10, instead of adding a new element to the HashSet, now it “sets” a bit in the set (the bit at the specified position is now true). But there are important changes at line 13. The method removeAll was changed, and now the array doesn’t require a cast anymore. And the it is not necessary to cast the elements from HashSet anymore, as now the bit in the index position of the set is set to true. So the extractIndices method could be removed.
http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array

System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy



The difference is that Arrays.copyOf does not only copy elements, it also creates a new array.System.arrayCopy copies into an existing array.

If we read the source code of Arrays.copyOf(), we can see that it uses System.arraycopy().

public static int[] copyOf(int[] original, int newLength) { 
   int[] copy = new int[newLength]; 
   System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); 
   return copy; 
}
     * for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
     *     // operate on index i here

     * }

     * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
     *     // operate on index i here
     *     if (i == Integer.MAX_VALUE) {
     *         break; // or (i+1) would overflow
     *     }
http://www.programcreek.com/2013/11/start-from-length-length-in-java/
After an array is created, its length never changes[1]. The array's length is available as a final instance variable length. Therefore, length can be considered as a defining attribute of an array.

Q2. Why there is not a class "Array" defined similarly like "String"?

Q3. Why String has length() method?
The backup data structure of a String is a char array. There is no need to define a field that is not necessary for every application.

String.java
    private final char value[];
    public int length() {
        return value.length;
    }
null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.
The Java Virtual Machine specification does not mandate a concrete value encoding null.
From the diagram of JVM run-time data areas, we know that since each method has a private stack frame within the thread's steak, the local variable are located on that frame.
// this will create a new arraylist and copy all data to it.
public static boolean useList(String[] arr, String targetValue) {
 return Arrays.asList(arr).contains(targetValue);
}
4 types of Java inner classes
1. Static Nested Classes
2. Member Inner Class -- don't use it unless have to
Member class is instance-specific. It has access to all methods, fields, and the Outer's this reference.
3. Method-Local Inner Classes
4. Anonymous Inner Classes
What Is Inner Interface in Java?
There are several compelling reasons for using inner interface:
  • It is a way of logically grouping interfaces that are only used in one place.
  • It increases encapsulation.
  • Nested interfaces can lead to more readable and maintainable code
One example of inner interface used in java standard library is java.util.Map and Java.util.Map.Entry. Here java.util.Map is used also as a namespace. Entry does not belong to the global scope, which means there are many other entities that are Entries and are not necessary Map's entries. This indicates that Entry represents entries related to the Map.

Static class is like a static method, it can only access outer class members through objects. Non-static class can access any member of the outer class.

http://www.programcreek.com/2013/04/what-are-the-frequently-asked-questions-about-constructors-in-java/
sub class constructor has to invoke super class instructor, either explicitly by programmer or implicitly by compiler. For either way, the invoked super constructor has to be defined.
For class access level, the keyword can be public or no explicit modifier(package-private). For member access level, the keyword can be publicprotected, package-private (no explicit modifier), or private.
Efficient Counter in Java
2. The Better Counter
HashMap<String, MutableInteger> newCounter = new HashMap<String, MutableInteger>(); 
 
for (String a : sArr) {
 if (newCounter.containsKey(a)) {
  MutableInteger oldValue = newCounter.get(a);
  oldValue.set(oldValue.get() + 1);
 } else {
  newCounter.put(a, new MutableInteger(1));
 }
}
The HashMap.put(key, value) method returns the key's current value. This is useful, because we can use the reference of the old value to update the value without searching one more time!
HashMap<String, MutableInteger> efficientCounter = new HashMap<String, MutableInteger>();
 
for (String a : sArr) {
 MutableInteger initValue = new MutableInteger(1);
 MutableInteger oldValue = efficientCounter.put(a, initValue);
 
 if(oldValue != null){
  initValue.set(oldValue.get() + 1);
 }
}
Better Approach (without containsKey):
HashMap<String, MutableInteger> efficientCounter2 = new HashMap<String, MutableInteger>();
for (int i = 0; i < NUM_ITERATIONS; i++) {
 for (String a : sArr) {
  MutableInteger value = efficientCounter2.get(a);
 
  if (value != null) {
   value.set(value.get() + 1);
  } else {
   efficientCounter2.put(a, new MutableInteger(1));
  }
 }
}
Better Approach (without containsKey, with AtomicInteger):
HashMap<String, AtomicInteger> atomicCounter = new HashMap<String, AtomicInteger>();
for (int i = 0; i < NUM_ITERATIONS; i++) {
 for (String a : sArr) {
  AtomicInteger value = atomicCounter.get(a);
 
  if (value != null) {
   value.incrementAndGet();
  } else {
   atomicCounter.put(a, new AtomicInteger(1));
  }
 }
}
Better Approach (without containsKey, with int[]):
HashMap<String, int[]> intCounter = new HashMap<String, int[]>();
for (int i = 0; i < NUM_ITERATIONS; i++) {
 for (String a : sArr) {
  int[] valueWrapper = intCounter.get(a);
 
  if (valueWrapper == null) {
   intCounter.put(a, new int[] { 1 });
  } else {
   valueWrapper[0]++;
  }
 }
}
http://blog.pengyifan.com/most-efficient-way-to-increment-a-map-value-in-java-only-search-the-key-once/
http://www.programcreek.com/2014/01/java-8-counter/
Stream<String> stream = Stream.of(arr).parallel();
Map<String, Long> counter = stream.collect(Collectors.groupingBy(String::toString, Collectors.counting()));

http://1001javatips.com/
The default type for floating point numbers is double.

float f = 3.4;  needs a cast.
float f = 3.4f; works.
float f = 3;  works without a cast.  See widening rules

■  Class-level variables get initialized with their respective defaults.  Method-level or block-level variables don’t ever get initialized.
An exception to the previous rule is arrays.  Arrays always do get initialized, no matter where they reside - at the class level, method level, or block level.
http://www.java-samples.com/showtutorial.php?tutorialid=261
NameWidth in BitsRange
double641 .7e–308 to 1.7e+308
float323 .4e–038 to 3.4e+038
float
The type float specifies a single-precision value that uses 32 bits of storage.
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( )cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
http://stackoverflow.com/questions/27598078/float-and-double-datatype-in-java
By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.
The solution is to not to use float or double but to use java class BigDecimal instead. Use always BigDecimal.
http://www.cnblogs.com/grandyang/p/4946889.html
14.2 In Java, does the finally block get executed if we insert a return statement inside the try block of a try-catch-finally?
这道题问我们Java中的finally块是否会被执行,当我们在try中加入了返回return。
答案是即便try中加入了return或者continue或者break等命令,finally块仍然会被执行。但是下列两种情况下finally里的内容不会被执行:
1. 当虚拟机Virtual Machine在try/catch模块中就退出了的时候
2. 当线程在处理try/catch模块就结束了的时候
http://www.cnblogs.com/grandyang/p/4942457.html
14.1 In terms of inheritance, what is the effect of keeping a constructor private?
这道题问我们用继承特性时,如果建立一个私有的构建函数会怎样。
只有能访问该函数的私有变量或函数的东西才能访问私有构建函数,比如内部类就可以访问,比如类A是类Q的一个内部类,那么Q的其他内部类可以访问类A的私有构建函数。
由于一个子类可以调用父类的构建函数,类A可以被继承,所以只有类A的子类或者是类Q的其他子类可以访问类A的私有构建函数。
http://www.ticmy.com/?p=43
1
2
int i = 0;
i = i++;
结果还是0
为什么?
程序的执行顺序是这样的:因为++在后面,所以先使用i,“使用”的含义就是i++这个表达式的值是0,但是并没有做赋值操作,它在整个语句的最后才做赋值,也就是说在做了++操作后再赋值的,所以最终结果还是0
让我们看的更清晰点:
1
2
int i = 0;//这个没什么说的
i = i++;//等效于下面的语句:
1
2
3
int temp = i;//这个temp就是i++这个表达式的值
i++; //i自增
i = temp;//最终,将表达式的值赋值给i
http://www.baeldung.com/java-read-lines-large-file
3. Streaming Through the File
FileInputStream inputStream = null;
Scanner sc = null;
try {
    inputStream = new FileInputStream(path);
    sc = new Scanner(inputStream, "UTF-8");
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        // System.out.println(line);
    }
    // note that Scanner suppresses exceptions
    if (sc.ioException() != null) {
        throw sc.ioException();
    }
} finally {
    if (inputStream != null) {
        inputStream.close();
    }
    if (sc != null) {
        sc.close();
    }
}

4. Streaming with Apache Commons IO

?
1
2
3
4
5
6
7
8
9
LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");
try {
    while (it.hasNext()) {
        String line = it.nextLine();
        // do something with line
    }
} finally {
    LineIterator.closeQuietly(it);
}
使用Java(sigar)获取系统信息
https://github.com/hyperic/sigar


http://www.baeldung.com/java-blogs
http://liujiacai.net/blog/2015/11/20/strings/

UTF-32

UTF-32 编码是 Unicode 最直接的存储方式,用 4 个字节来分别表示 code point 中的 4 个字节,也是 UTF-*编码家族中唯一的一种定长编码(fixed-length encoding)。UTF-32 的好处是能够在O(1)时间内找到第 N 个字符,因为第 N 个字符的编码的起点是 N*4 个字节,当然,劣势更明显,四个字节表示一个字符,别说以英文为母语的人不干,我们中国人也不干了。

UTF-16

UTF-16 最少可以采用 2 个字节表示 code point,需要注意的是,UTF-16 是一种变长编码(variable-length encoding),只不过对于 65535 之内的 code point,采用 2 个字节表示而已。如果想要表示 65535 之上的字符,需要一些 hack 的手段,具体可以参考wiki UTF-16#U.2B10000_to_U.2B10FFFF。很明显,UTF-16 比 UTF-32 节约一半的存储空间,如果用不到 65535 之上的字符的话,也能够在O(1)时间内找到第 N 个字符。
UTF-16 与 UTF-32 还有一个不明显的缺点。我们知道不同的计算机存储字节的顺序是不一样的,这也就意味着U+4E2D 在 UTF-16 可以保存为4E 2D,也可以保存成2D 4E,这取决于计算机是采用大端模式还是小端模式,UTF-32 的情况也类似。为了解决这个问题,引入了 BOM (Byte Order Mark),它是一特殊的不可见字符,位于文件的起始位置,标示该文件的字节序。对于 UTF-16 来说,BOM 为U+FEFF(FF 比 FE 大 1),如果某 以 UTF-16 编码的文件以FF FE开始,那么就意味着字节序为小端模式,如果以FE EE开始,那么就是大端模式

UTF-8

UTF-16 对于以英文为母语的人来说,还是有些浪费了,这时聪明的人们(准确说是Ken ThompsonRob Pike)又发明了另一个编码——UTF-8。在 UTF-8 中,ASCII 字符采用单字节。其实,UTF-8 前 128 个字符与 ASCII 字符编码方式一致;扩展的拉丁字符像ñö等采用2个字节存储;中文字符采用 3 个字符存储,使用频率极少字符采用 4 个字节存储。由此可见,UTF-8 也是一种变长编码(variable-length encoding)
UTF-8 的编码规则很简单,只有二条:
  1. 对于单字节的符号,字节的第一位设为0,后面7位为这个符号的 code point。因此对于英语字母,UTF-8编码和ASCII码是相同的。
  2. 对于n字节的符号,第一个字节的前n位都设为1,第n+1位设为0,后面字节的前两位一律设为10。剩下的没有提及的二进制位,全部为这个符号的 code point。
 UTF-8 编码规则UTF-8 编码规则
通过上面这两个规则,UTF-8 就不存在字节顺序在大小端不同的情况,所以用 UTF-8 编码的文件在任何计算机中保存的字节流都是一致的,这是其很重要一优势;UTF-8 的另一大优势在于对 ASCII 字符超节省空间,存储扩展拉丁字符与 UTF-16 的情况一样,存储汉字字符比 UTF-32 更优。
UTF-8 的一劣势是查找第 N 个字符时需要O(N) 的时间,也就是说,字符串越长,就需要更长的时间来查找其中的每个字符。其次是在对字节流解码、字符编码时,需要遵循上面两条规则,比 UTF-16、UTF-32 略麻烦。
随着互联网的兴起,UTF-8 是逐渐成为使用范围最广的编码方案。
https://news.ycombinator.com/item?id=1229493
http://blog.coverity.com/2014/04/09/why-utf-16/

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts