Java FAQ

来自博客的总结

实例构造器是不是静态方法?
从 Java 语言的 static关键字的角度看,实例构造器不是“静态方法”。

来自知乎的问题

往 Java 泛型类中方法传一个对象引用的参数,但是该方法的参数为什么不能调用该对象的方法?

因为 Java 的泛型设计跟 C++ 的模版是不一样的。

  • C++ 的模版的基本思路是在某个模版类型或模版函数被实例化的时候,将实际模版参数传入模版并展开,然后再做类型检查(实际过程更复杂一些,展开跟类型检查之间有交互,不过简化看其基本思路的话看作是先展开再类型检查也够用);
  • 而 Java 的泛型类型或泛型方法则是泛型参数在声明时带有多少类型信息,在该类型或方法内就只能用多少信息。在泛型类型或泛型参数实例化的地方仅仅需要检查传入的泛型参数与声明的限制是否匹配,而不会在实例化后再对类型或方法内部做类型检查。
如何理解《深入理解 Java 虚拟机》第二版中对 String.intern() 方法的讲解中所举的例子
在 Oracle JDK7u45 上做的实验显示,这个版本的 JDK / JRE 上,字符串常量池里的”java”字符串来自 sun.misc.Version 类
为什么函数调用要用栈实现?
被调用者的局部信息所占空间的分配总是后于调用者的(后入),而其释放则总是先于调用者的(先出),所以正好可以满足栈的LIFO顺序,选用栈这种数据结构来实现调用栈是一种很自然的选择。

来自 StackOverflow 的问题

Why is it faster to process a sorted array than an unsorted array?

This is a Branch predictor pitfall. A general rule of thumb is to avoid data-dependent branching in critical loop.

Is Java “pass-by-reference” or “pass-by-value”?

The Java Spec says that everything in Java is pass-by-value. There is no such thing as pass-by-reference in Java.

The key to understanding this is that something like

Dog myDog;

is not a Dog; it’s actually a pointer to a Dog.

Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.

Java’s +=, -=, *=, /= compound assignment operators

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.

Avoiding != null statements

Where null is not a valid response: Either use assert or throw an exception.2. Where it is a valid response in terms of the contract: With methods that return collections, it’s easy to return empty collections (or arrays) instead of nulls pretty much all the time; With non-collections, return null object just like Null Object pattern.

Differences between HashMap and Hashtable?

Hashtable is synchronized, wheraeas HashMap is not.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.

Read/convert an InputStream to a String

Using Apache Commons IOUtils

Why is char[] preferred over String for passwords in Java?

String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage.

Create ArrayList from array

Given

javaElement[] array = {new Element(1), new Element(2), new Element(3)};

The simplest answer is to do:

javaList<Element> list = Arrays.asList(array);

Generating random integers in a specific range

In practice, the java.util.Random class is often preferable to java.lang.Math.random().

Why is printing “B” dramatically slower than printing “#”?

Pure speculation is that you’re using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character.

Creating a memory leak with Java

Here’s a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java:

The application creates a long-running thread (or use a thread pool to leak even faster).2. The thread loads a class via an (optionally custom) ClassLoader.3. The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster.4. The thread clears all references to the custom class or the ClassLoader it was loaded from.5. Repeat.

When to use LinkedList over ArrayList?

LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

What is a serialVersionUID and why should I use it?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization.

How to test a class that has private methods, fields or inner classes?

If you have somewhat of a legacy application, and you’re not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.

How can I create an executable JAR with dependencies using Maven?

Maven documentation maven.apache.org/plugins/maven-assembly-plugin

Initialization of an ArrayList in one line

In most cases just use

javaArrayList<String> list = new ArrayList<String>(Arrays.asList("A","B","C"));

or (this is known as an “double brace initialization”)

javaArrayList<String> list = new ArrayList<String>(){{add("A"); add("B"); add("C");}};

See stackoverflow.com/questions/924285 for more information about the double-brace initialization, pros and cons.

Why does this code using random strings print “hello world”?

Every Random constructed with the same seed will generate the same pattern of numbers every time.

How can I test if an array contains a certain value?

javaArrays.asList(yourArray).contains(yourValue)

“implements Runnable” vs. “extends Thread”

Yes: implements Runnable is the preferred way to do it, IMO. You’re not really specialising the thread’s behaviour.

Does “finally” always execute in Java?

finally will be called.

How do I call one constructor from another in Java?

Yes, it’s possible. To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

Lookup enum by string value

Yes, Blah.valueOf("A") will give you Blah.A.

Breaking out of nested loops in Java

You can use break with a label for the outer loop.

Java inner class and static nested class

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

  • Static nested classes are accessed using the enclosing class name.

  • Objects that are instances of an inner class exist within an instance of the outer class. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object.

see: Java Tutorial - Nested Classes

What is reflection and why is it useful?

The name reflection is used to describe code which is able to inspect and dynamically call classes, methods, attributes, etc. at runtime.

One very common use case in Java is the usage with annotations. There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html

Why is executing Java code in comments with certain Unicode characters allowed?

Unicode decoding takes place before any other lexical translation. The key benefit of this is that it makes it trivial to go back and forth between ASCII and any other encoding.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

The version number shown describes the version of the JRE the class file is compatible with. To fix the actual problem you should try to either run the Java code with a newer version of Java JRE or specify the target parameter to the Java compiler to instruct the compiler to create code compatible with earlier Java versions.

How to generate a random alpha-numeric string?

use SecureRandom

What’s the simplest way to print a Java array?

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays.


Unsolved Problem

Using java.net.URLConnection to fire and handle HTTP requests

How to avoid Java code in JSP files?

Dealing with “java.lang.OutOfMemoryError: PermGen space” error

How do you assert that a certain exception is thrown in JUnit 4 tests?

如何理解ByteCode、IL、汇编等底层语言与上层语言的对应关系?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值