Thursday, July 16, 2015

Java Miscs



Traps
http://www.javaworld.com/article/2073330/the-contains-trap-in-java-collections.html
Collection.contains(Object) accepts an Object, which means it essentially accepts an instance of any Java class. This is where the potential trap lies. If one passes in an instance of a class other than the the type of classes that can be stored in a particular collection, it can be that this method will simply return false

I have demonstrated how the Collection.contains(Object) method (including the Map.containsKey(Object) method) can behave differently depending on how the particular collection implementation decides to throw or not throw the option ClassCastException when a provided object is not of a relevant class to the objects stored in that collection. 

https://stackoverflow.com/questions/5682625/why-do-integer-div-and-mod-round-towards-zero
in Java is the result of x/y and x%y well-defined even for negative operands. Surprisingly, it's defined by rounding towards zero, and not by rounding down (i.e., towards negative infinity).

It's easier to implement a division routine if you can round toward zero. Often, a division involving a negative is sign-flipped, and then the division carried out on a positive equivalent, and then the answer flipped back again. So the effect is naturally going to be round toward zero.

Here's one example where it's useful, however slightly:

maxPage = (rows.length - 1) / ROWS_PER_PAGE
(No need to special case for maxPage = 0 when rows.length = 0, assuming ROWS_PER_PAGE > 1.)

https://stackoverflow.com/questions/37308248/java-integer-division-doesnt-give-floor-for-negative-numbers
I was trying to use java's integer division, and it supposedly takes the floor. However, it rounds towards zero instead of the floor.
floorDiv() from Java.Math that does exactly what you want.

static long floorDiv(long x, long y)
Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
public static int floorDiv(int x, int y) {
    int r = x / y;
    // if the signs are different and modulo not zero, round down
    if ((x ^ y) < 0 && (r * y != x)) {
        r--;
    }
    return r;
}
https://www.cs.umd.edu/~clin/MoreJava/Intro/expr-int-div.html
/ is the division operator. If the types of the operands are double, then "real" division is performed. Real division is normal division as you learned in grade school. Division is approximate on a computer because you can't do infinitely precise division (recall that double values have finite precision, so there is usually a tiny, but unavoidable error representing real numbers). The result of dividing a double by a double is a double.
However, if both expressions have type int, then the result is an int. Does that sound strange? What is the result of evaluating 7 / 3?
Java does integer division, which basically is the same as regular real division, but you throw away the remainder (or fraction). Thus, 7 / 3 is 2 with a remainder of 1. Throw away the remainder, and the result is 2.
Integer division can come in very handy. Even if you don't see a use for it now, it is used quite often.
What happens if you really want an answer that's double. That is, you want the answer to be 2.33333333 or something close.
One way is to cast the denominator to double. You do this as 7 / (double) 3. Casting is an operator that creates a temporary double value. Thus it creates a temporary 3.0 double.
When one of the operands to a division is a double and the other is an int, Java implicitly (i.e. behind your back) casts the int operand to a double. Thus, Java performs the real division 7.0 / 3.0.
https://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.

Integer division of course returns the true result of division rounded towards zero. The result of 0.333... is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)

Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333....
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
In order to perform any sort of floating-point arithmetic with integers, you need to convert (read: cast) at least one of the operands to a float type.
https://stackoverflow.com/questions/1293819/why-does-java-implicitly-without-cast-convert-a-long-to-a-float
long l = 123456789L;
float f = l;
System.out.println(f);  // outputs 1.23456792E8
Given that a long has greater bit-depth than a float, I would expect that an explicit cast would be required in order for this to compile. And not surprisingly, we see that we have lost precision in the result.

Why is a cast not required here?

5.1.2 Widening Primitive Conversion

The following 19 specific conversions on primitive types are called the widening primitive conversions:

byte to short, int, long, float, or double
short to int, long, float, or double
char to int, long, float, or double
int to long, float, or double
long to float or double
float to double
Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

...

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value
To put it another way, the JLS distinguishes between a loss of magnitude and a loss of precision.

int to byte for example is a (potential) loss of magnitude because you can't store 500 in a byte.

long to float is a potential loss of precision but not magnitude because the value range for floats is larger than that for longs.

So the rule is:

Loss of magnitude: explicit cast required;
Loss of precision: no cast required.

 Float can store in exponential form as is we write it. '23500000000' is stored as '2.35e10' .So, float has space to occupy the range of values of long. Storing in exponential form is also the reason for precision loss.

return ToStringBuilder.reflectionToString(this);

We use ToStringBuilder.reflectionToString() in our objects' toString() methods. We have not had any issues running like this in a production environment. Granted, we rarely use the toString() method.
We also use BeanUtils.describe(), but for another purpose. BeanUtils uses PropertyUtilsBeanwhich keeps an internal cache of beans for which it has performed introspection. It would seem that this would give it a performance advantage over the other, but a little poking around in the reflectionToString source and it seems that since it ultimately relies on the implementation of java.lang.Class, caching comes into play there as well.
Either looks like a viable choice, but BeanUtils.describe() will return a Map of properties where reflectionToString will return a formatted String. I guess it depends on what you want to do with the output.
I would suggest that if your application is heavily dependent on calling toString() on your objects, having a specific implementation might be more beneficial.
The following code snippet shows how to selectively exclude the best friend field, then only add the ID value. You have to check for null to avoid a NPE.
@Override
public String toString() {
  ReflectionToStringBuilder builder = new ReflectionToStringBuilder(this);
  builder.setExcludeFieldNames("bestfriend");
  builder.append("bestfriend", (bestfriend == null) ? "None" : bestfriend.id);
  return builder.build();
}
  public String toString() {
    return ReflectionToStringBuilder.toString(this);
  }

  public boolean equals(Object pObject) {
    return EqualsBuilder.reflectionEquals(this, pObject);
  }

  public int compareTo(Object pObject) {
    return CompareToBuilder.reflectionCompare(this, pObject);
  }

  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }
http://stackoverflow.com/questions/20514025/compare-utils-for-comparators
Try Guava's ComparisonChain: - use this.
public int compareTo(Foo that) {
     return ComparisonChain.start()
         .compare(this.aString, that.aString)
         .compare(this.anInt, that.anInt)
         .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
         .result();

Java 8 has some functions that allow construction and chaining of Comparators:
Note this is not null-safe. u still need check whether o1,o2 is null, and check whether o1/o2.getName is null.
Comparator.comparing(Pojo::isExternal)
          .thenComparing(Pojo::getName).compare(o1,o2);
http://www.java2s.com/Code/Java/Development-Class/TurnSystemoutintoaPrintWriter.htm
    PrintWriter out = new PrintWriter(System.out, true);

http://javarevisited.blogspot.com/2013/01/how-to-decompile-class-file-in-java-eclipse-javap-example.html
How to see bytecode from .class file
javap -c Hello

javap Hello
Why character array is better than String for Storing password in Java
http://javarevisited.blogspot.com/2012/03/why-character-array-is-better-than.html
1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. 
2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] anddeprecated getText() method which returns password in clear text stating security reason. 
3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed.

http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/
A) You must implement Cloneable interface.
B) You must override clone() method from Object class. [Its weird. clone() method should have been in Cloneable interface.]
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:
1) x.clone() != x will be true
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
3) x.clone().equals(x) will be true, this is not an absolute requirement.
*/
protected native Object  [More ...] clone() throws CloneNotSupportedException;
  1. First statement guarantees that cloned object will have separate memory address assignment.
  2. Second statement suggest that original and cloned objects should have same class type, but it is not mandatory.
  3. Third statement suggest that original and cloned objects should have be equal using equals() method, but it is not mandatory.
protected Object clone() throws CloneNotSupportedException {
    Employee cloned = (Employee)super.clone();
    cloned.setDepartment((Department)cloned.getDepartment().clone());
    return cloned;
}
SomeObject cloned = org.apache.commons.lang.SerializationUtils.clone(someObject);

public static  T clone(T t) throws Exception {
    //Check if T is instance of Serializeble other throw CloneNotSupportedException
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //Serialize it
    serializeToOutputStream(t, bos);
    byte[] bytes = bos.toByteArray();
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
    //Deserialize it and return the new instance
    return (T)ois.readObject();
}
1) When you don’t know whether you can call the clone() method of a particular class as you are not sure if it is implemented in that class, you can check with checking if the class is instance of “Cloneable” interface as below.
if(obj1 instanceof Cloneable){
    obj2 = obj1.clone();
}
//Dont do this. Cloneabe dont have any methods
obj2 = (Cloneable)obj1.clone();
2) No constructor is called on the object being cloned. As a result, it is your responsibility, to make sure all the members have been properly set. Also, if you are keeping track of number of objects in system by counting the invocation of constructors, you got a new additional place to increment the counter.
http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying-an-instance
for deep cloning (clones the entire object hierarchy):
  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable
  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable
for shallow cloning (clones only the first level properties):
All approaches to copy objects in Java have serious flaws:
Clone
  1. The clone() method is protected, so you can't call it directly unless the class in question overrides it with a public method.
  2. clone() doesn't call the constructor. Any constructor. It will allocate memory, assign the internal class field (which you can read via getClass()) and copy the fields of the original.
For more issues with clone(), see item 11 of Joshua Bloch's book "Effective Java, Second Edition"
Serialize
Serialize is even worse; it has many of the flaws of clone() and then some. Joshua has a whole chapter with four items for this topic alone.

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