跳至主要内容

博文

目前显示的是 二月, 2018的博文

How to Implement String Case Insensitive Compare?

How to Implement String Case Insensitive Compare? How would you implement a String Comparator used in String#compareToIgnoreCase ? I may convert all character to upper case then compare like the following does: int n1 = s1 . length ( ) ; int n2 = s2 . length ( ) ; int min = Math . min ( n1 , n2 ) ; for ( int i = 0 ; i < min ; i ++ ) { char c1 = Character . toUpperCase ( s1 . charAt ( i ) ) ; char c2 = Character . toUpperCase ( s2 . charAt ( i ) ) ; if ( c1 != c2 ) { return c1 - c2 ; } } return n1 - n2 ; It seems work and we may also use toLowerCase to replace toUpperCase . But the implementation in JDK source code doesn’t agree: int n1 = s1 . length ( ) ; int n2 = s2 . length ( ) ; int min = Math . min ( n1 , n2 ) ; for ( int i = 0 ; i < min ; i ++ ) { char c1 = s1 . charAt ( i ) ; char c2 = s2 . charAt ( i ) ; if ( c1 != c2 ) { c1 = Character . to...

Get Java Generic Type?

Get Java Generic Type? Tony is now implementing some persistence/serialization library using Java. Because the implementation of generic of Java is the erasure, the generic has many limitations . The first interface Tony needed to implement is creating a new instance by using type parameter. public class SomeLib < T > { public T fromString ( String string ) { } } Extra Class Because the type parameter is erased at runtime, Tony can’t use new T() to create a new instance or use T.class to get real class etc. The common way to do the similar things is to put an extra Class parameter in interface: public class SomeLib { public < T > T fromString ( String string , Class < T > clazz ) { T t = ( T ) clazz . newInstance ( ) ; } } Superclass Workaround This way works, but also very inconvenient. If Tony want to deserialize a type with nested generic types, the interfaces may become: public < T , S >...