From 342ea67efc8bb63660a5deed8335c5f3e731e9b8 Mon Sep 17 00:00:00 2001 From: Chen Xie Date: Mon, 4 Apr 2016 16:03:21 -0700 Subject: [PATCH 001/108] Create why-is-printing-b-dramatically-slower-than-printing.md --- ...ing-b-dramatically-slower-than-printing.md | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 contents/why-is-printing-b-dramatically-slower-than-printing.md diff --git a/contents/why-is-printing-b-dramatically-slower-than-printing.md b/contents/why-is-printing-b-dramatically-slower-than-printing.md new file mode 100644 index 0000000..8df683f --- /dev/null +++ b/contents/why-is-printing-b-dramatically-slower-than-printing.md @@ -0,0 +1,64 @@ +# 为什么打印"B"会明显的比打印"#"慢 + +## 问题 + +我生成了两个`1000`x`1000`的矩阵: + +第一个矩阵:`O`和`#`。 +第二个矩阵:`O`和`B`。 + +使用如下的代码,生成第一个矩阵需要8.52秒: + + Random r = new Random(); + for (int i = 0; i < 1000; i++) { + for (int j = 0; j < 1000; j++) { + if(r.nextInt(4) == 0) { + System.out.print("O"); + } else { + System.out.print("#"); + } + } + + System.out.println(""); + } + + +而使用这段代码,生成第二个矩阵花费了259.152秒: + + Random r = new Random(); + for (int i = 0; i < 1000; i++) { + for (int j = 0; j < 1000; j++) { + if(r.nextInt(4) == 0) { + System.out.print("O"); + } else { + System.out.print("B"); //only line changed + } + } + + System.out.println(""); + } + +如此大的运行时间差异的背后究竟是什么原因呢? + +--- + +正如评论中所建议的,只打印`System.out.print("#");`用时7.8871秒,而`System.out.print("B");`则给出`still printing...`。 + +另外有人指出这段代码对他们来说是正常的, 我使用了[Ideone.com](http://ideone.com),这两段代码的执行速度是相同的。 + +测试条件: + + - 我在Netbeans 7.2中运行测试,由控制台显示输出 + - 我使用了`System.nanoTime()`来计算时间 + + ## 解答 + + *纯粹的推测*是因为你使用的终端尝试使用[单词换行][1]而不是字符换行,并且它认为`B`是一个单词而`#`却不是。所以当它到达行尾并且寻找一个换行的地方的时候,如果是`#`就可以马上换行;而如果是`B`,它则需要花更长时间搜索,因为可能会有更多的内容才能换行(在某些终端会非常费时,比如说它会先输出退格再输出空格去覆盖被换行的那部分字符)。 + +但这都只是纯粹的推测。 + + + [1]: http://en.wikipedia.org/wiki/Word_wrap + + +stackoverflow原址:http://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing From 92e3f0247c18d63e258977002cb0c8be6159d510 Mon Sep 17 00:00:00 2001 From: Chen Xie Date: Mon, 4 Apr 2016 16:06:44 -0700 Subject: [PATCH 002/108] remove unnecessary spaces --- .../why-is-printing-b-dramatically-slower-than-printing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/why-is-printing-b-dramatically-slower-than-printing.md b/contents/why-is-printing-b-dramatically-slower-than-printing.md index 8df683f..7ff8dfd 100644 --- a/contents/why-is-printing-b-dramatically-slower-than-printing.md +++ b/contents/why-is-printing-b-dramatically-slower-than-printing.md @@ -51,9 +51,9 @@ - 我在Netbeans 7.2中运行测试,由控制台显示输出 - 我使用了`System.nanoTime()`来计算时间 - ## 解答 +## 解答 - *纯粹的推测*是因为你使用的终端尝试使用[单词换行][1]而不是字符换行,并且它认为`B`是一个单词而`#`却不是。所以当它到达行尾并且寻找一个换行的地方的时候,如果是`#`就可以马上换行;而如果是`B`,它则需要花更长时间搜索,因为可能会有更多的内容才能换行(在某些终端会非常费时,比如说它会先输出退格再输出空格去覆盖被换行的那部分字符)。 +*纯粹的推测*是因为你使用的终端尝试使用[单词换行][1]而不是字符换行,并且它认为`B`是一个单词而`#`却不是。所以当它到达行尾并且寻找一个换行的地方的时候,如果是`#`就可以马上换行;而如果是`B`,它则需要花更长时间搜索,因为可能会有更多的内容才能换行(在某些终端会非常费时,比如说它会先输出退格再输出空格去覆盖被换行的那部分字符)。 但这都只是纯粹的推测。 From dd3587c860b86b36f2ce4f133265827ddbcbaf7f Mon Sep 17 00:00:00 2001 From: Chen Xie Date: Mon, 4 Apr 2016 17:51:43 -0700 Subject: [PATCH 003/108] Update why-is-printing-b-dramatically-slower-than-printing.md --- ...ing-b-dramatically-slower-than-printing.md | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/contents/why-is-printing-b-dramatically-slower-than-printing.md b/contents/why-is-printing-b-dramatically-slower-than-printing.md index 7ff8dfd..970dbde 100644 --- a/contents/why-is-printing-b-dramatically-slower-than-printing.md +++ b/contents/why-is-printing-b-dramatically-slower-than-printing.md @@ -51,7 +51,7 @@ - 我在Netbeans 7.2中运行测试,由控制台显示输出 - 我使用了`System.nanoTime()`来计算时间 -## 解答 +## 解答一 *纯粹的推测*是因为你使用的终端尝试使用[单词换行][1]而不是字符换行,并且它认为`B`是一个单词而`#`却不是。所以当它到达行尾并且寻找一个换行的地方的时候,如果是`#`就可以马上换行;而如果是`B`,它则需要花更长时间搜索,因为可能会有更多的内容才能换行(在某些终端会非常费时,比如说它会先输出退格再输出空格去覆盖被换行的那部分字符)。 @@ -61,4 +61,54 @@ [1]: http://en.wikipedia.org/wiki/Word_wrap +##解答二 + +我用Eclipse和Netbeans 8.0.2做了测试,他们的Java版本都是1.8;我用了`System.nanoTime()`来计时。 + +##Eclipse: + +我得到了**用时相同的结果** - 大约**1.564秒**。 + +##Netbeans: + +* 使用"#": **1.536秒** +* 使用"B": **44.164秒** + +所以看起来像是Netbeans输出到控制台的性能问题。 + +在做了更多研究以后我发现问题所在是Netbeans [换行][1] 的最大缓存(这并不限于`System.out.println`命令),参见以下代码: + + for (int i = 0; i < 1000; i++) { + long t1 = System.nanoTime(); + System.out.print("BBB......BBB"); \\<-contain 1000 "B" + long t2 = System.nanoTime(); + System.out.println(t2-t1); + System.out.println(""); + } + +每一个循环所花费的时间都不到1毫秒,除了 **每第五个循环**会花掉大约225毫秒。像这样(单位是毫秒): + + BBB...31744 + BBB...31744 + BBB...31744 + BBB...31744 + BBB...226365807 + BBB...31744 + BBB...31744 + BBB...31744 + BBB...31744 + BBB...226365807 + . + . + . + +以此类推。 + +##总结: + +1. 使用Eclipse打印"B"完全没有问题 +1. Netbeans有换行的问题但是可以被解决(因为在Eclipse并没有这个问题)(而不用在B后面添加空格("B "))。 + + [1]: http://en.wikipedia.org/wiki/Line_wrap_and_word_wrap + stackoverflow原址:http://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing From 463f6335211454da3adf08dafff11f833f17ecd9 Mon Sep 17 00:00:00 2001 From: Chen Xie Date: Tue, 5 Apr 2016 15:48:04 -0700 Subject: [PATCH 004/108] Create how-can-i-pad-an-integers-with-zeros-on-the-left.md --- ...i-pad-an-integers-with-zeros-on-the-left.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md diff --git a/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md b/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md new file mode 100644 index 0000000..27809e0 --- /dev/null +++ b/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md @@ -0,0 +1,18 @@ +# 如何用0向左补齐一个整数? + +## 问题 + +在Java中如何把一个整数转化为字符串并且用0向左补齐呢? + +我基本上是希望把一个不大于9999的整数用0补齐 (比如说1="0001")。 + +## 解答 + + String.format("%05d", yournumber); + +可以将一个五位数用0补齐。 + + +https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html + +Stackoverflow链接:http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left From 79a74a6783d48f65c522ed75167ec059162534a7 Mon Sep 17 00:00:00 2001 From: jam Date: 2016年4月17日 20:22:17 +0800 Subject: [PATCH 005/108] =?UTF-8?q?java=E7=9A=84vector=E7=B1=BB=E4=B8=BA?= =?UTF-8?q?=E4=BB=80=E4=B9=88=E8=A2=AB=E8=AE=A4=E4=B8=BA=E8=BF=87=E6=97=B6?= =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../why-is-java-vector-class-considered-obsolete-or-deprecated.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md diff --git a/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md b/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md new file mode 100644 index 0000000..e69de29 From 9f94d699bda038e20b09f42c3fa3b347d0110307 Mon Sep 17 00:00:00 2001 From: jssyjam Date: 2016年4月17日 20:24:12 +0800 Subject: [PATCH 006/108] Update why-is-java-vector-class-considered-obsolete-or-deprecated.md --- ...class-considered-obsolete-or-deprecated.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md b/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md index e69de29..5e23388 100644 --- a/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md +++ b/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md @@ -0,0 +1,21 @@ +## 为什么Java的```Vector```类被认为是过时的或者废弃的 +### 问题 +为什么java ```Vector```类被认为是一个遗留的,过时的或废弃的类?在并发操作时,使用它是无效的吗? + +如果我不想手动对对象实现同步,只想用一个线程安全的集合而无需创建底层数组的全新副本(如```CopyOnWriteArrayList```一样)。这种情况下,我使用```Vector```合理吗? + +然后就是关于栈的问题,它是Vector的一个子类,我应该用什么代替它? +### 回答 +Vector中对每一个独立操作都实现了同步,这通常不是我们想要的做法。对单一操作实现同步通常不是线程安全的(举个例子,比如你想遍历一个Vector实例。你仍然需要申明一个锁来防止其他线程在同一时刻修改这个Vector实例。如果不添加锁的话 + +通常会在遍历实例的这个线程中导致一个``` ConcurrentModificationException ```)同时这个操作也是十分慢的(在创建了一个锁就已经足够的前提下,为什么还需要重复的创建锁) + +当然,即使你不需要同步,Vector也是有锁的资源开销的。 + +总的来说,在大多数情况下,这种同步方法是存在很大缺陷的。正如Mr Brain Henk指出,你可以通过调用```Collections.synchronizedList```来装饰一个集合 -事实上 ```Vector``` 将"可变数组"的集合实现与"同步每一个方法"结合起来的做法是另一个糟糕的设计; + +各个装饰方法能够更明确的指示其关注的功能实现。 + +对于```Stack```这个类-我更乐于使用```Deque/ArrayDeque```来实现 + +stackoverflow讨论地址: http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated From 951f880e4cb83b7b8d32463b79fd338bddfa7f4b Mon Sep 17 00:00:00 2001 From: jam Date: 2016年4月17日 20:29:03 +0800 Subject: [PATCH 007/108] fanyi --- ...class-considered-obsolete-or-deprecated.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md b/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md index e69de29..cfbb754 100644 --- a/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md +++ b/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md @@ -0,0 +1,21 @@ +## 为什么Java的```Vector```类被认为是过时的或者废弃的 +### 问题 +为什么java ```Vector```类被认为是一个遗留的,过时的或废弃的类?在并发操作时,使用它是无效的吗? + +如果我不想手动对对象实现同步,只想用一个线程安全的集合而无需创建底层数组的全新副本(如```CopyOnWriteArrayList```一样)。这种情况下,我使用```Vector```合理吗? + +然后就是关于栈的问题,它是Vector的一个子类,我应该用什么代替它? +### 回答 +Vector中对每一个独立操作都实现了同步,这通常不是我们想要的做法。对单一操作实现同步通常不是线程安全的(举个例子,比如你想遍历一个Vector实例。你仍然需要申明一个锁来防止其他线程在同一时刻修改这个Vector实例。如果不添加锁的话 + +通常会在遍历实例的这个线程中导致一个``` ConcurrentModificationException ```)同时这个操作也是十分慢的(在创建了一个锁就已经足够的前提下,为什么还需要重复的创建锁) + +当然,即使你不需要同步,Vector也是有锁的资源开销的。 + +总的来说,在大多数情况下,这种同步方法是存在很大缺陷的。正如Mr Brain Henk指出,你可以通过调用```Collections.synchronizedList```来装饰一个集合 -事实上 ```Vector``` 将"可变数组"的集合实现与"同步每一个方法"结合起来的做法是另一个糟糕的设计; + +各个装饰方法能够更明确的指示其关注的功能实现。 + +对于```Stack```这个类-我更乐于使用```Deque/ArrayDeque```来实现 + +stackoverflow讨论地址: http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated From c2237304d294fd434a3b94e6a2de280212190a9f Mon Sep 17 00:00:00 2001 From: tangculijier <327493498@qq.com> Date: Tue, 3 May 2016 23:36:30 +0800 Subject: [PATCH 008/108] Create onvert-a-string-to-an-enum-in-java.md --- .../onvert-a-string-to-an-enum-in-java.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 contents/onvert-a-string-to-an-enum-in-java.md diff --git a/contents/onvert-a-string-to-an-enum-in-java.md b/contents/onvert-a-string-to-an-enum-in-java.md new file mode 100644 index 0000000..0e7fd5b --- /dev/null +++ b/contents/onvert-a-string-to-an-enum-in-java.md @@ -0,0 +1,30 @@ +##在java中把String转换给enum类 +------------------------------------- + +###问题 +假设有有个枚举类: +```java +public enum Blah +{ + A, B, C, D +} +``` +现在我想把这个String转成枚举类,比如说"A"应该等于Blash.A.该怎么做? + +------ +###回答1 +```java +Blah A = Blah.valueOf("A"); +``` +这样传入"A"会返回Balsh枚举类. +###回答2 +```java +Blah A =Enum.valueOf(Blah.class, "A"); +``` +同样可以得到该枚举类 + +**这两个方法都会传入的参数大小写敏感,这个例子如果传入"a",则会报错No enum const class Blah.a.** + +stackoverflow原址: http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java + + From 5d872de85b4ec8e05019d34cbe1d6b6a274ca4e5 Mon Sep 17 00:00:00 2001 From: ArronDon Date: Mon, 9 May 2016 22:28:44 +0800 Subject: [PATCH 009/108] Create how-does-the-java-for-each-loop-work.md --- .../how-does-the-java-for-each-loop-work.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 contents/how-does-the-java-for-each-loop-work.md diff --git a/contents/how-does-the-java-for-each-loop-work.md b/contents/how-does-the-java-for-each-loop-work.md new file mode 100644 index 0000000..8d58d0f --- /dev/null +++ b/contents/how-does-the-java-for-each-loop-work.md @@ -0,0 +1,23 @@ +## Java的foreach循环是如何工作的? +### 问题 +````java +List someList = new ArrayList(); +// add "monkey", "donkey", "skeleton key" to someList +for (String item : someList) { + System.out.println(item); +} +```` +如果不用for each语法,等价的循环语句是什么样的? +### 回答 +````java +for(Iterator i = someList.iterator(); i.hasNext(); ) { + String item = i.next(); + System.out.println(item); +} +```` +记住,如果需要在循环中使用i.remove;或者以某种方式获取实际的iterator,你不能使用for(:)语法,因为实际的Iterator很难被推断出来。 +正如Denis Bueno写的那样,这种代码对任何实现了Iterable接口的对象都奏效。 +此外,如果for(:)句法中右侧是一个数组而不是一个可迭代对象,那么内部代码用一个int型的计数器来防止数组越界。详见Java Language Specification: +http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2 + +stackoverflow链接:http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work From eae052735ee4dd49f0de606e27957bcb6cdfd034 Mon Sep 17 00:00:00 2001 From: Android-kk Date: 2016年5月18日 10:01:15 +0800 Subject: [PATCH 010/108] Update what-is-a-serialversionuid-and-why-should-i-use-it.md --- contents/what-is-a-serialversionuid-and-why-should-i-use-it.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md b/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md index 645bd54..321c58a 100644 --- a/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md +++ b/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md @@ -127,7 +127,7 @@ public void testversion1LWithExtraEmail() throws Exception { private static final long serialVersionUID = 2L; ``` -再次进行序列化,则会报错,如下: +再次进行反序列化,则会报错,如下: ``` java.io.InvalidClassException:Person local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2 ``` From 413b445728e3bb24abcdc16ca28aed8085e4c8dd Mon Sep 17 00:00:00 2001 From: unknown <陈恭帅> Date: 2016年5月19日 15:04:14 +0800 Subject: [PATCH 011/108] tianjiafanyi --- ...lets-work-instantiation-shared-variables-and-multithreading.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md diff --git a/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md b/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md new file mode 100644 index 0000000..e69de29 From f82979f88a8ca1c4f4fd7d4bedf77d650806de2f Mon Sep 17 00:00:00 2001 From: NothingOne Date: 2016年5月19日 16:43:01 +0800 Subject: [PATCH 012/108] Update what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.md --- ...be-considered-when-overriding-equals-and-hashcode-in-java.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.md b/contents/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.md index 1ed4300..f09120b 100644 --- a/contents/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.md +++ b/contents/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.md @@ -1,4 +1,4 @@ -##重写(Override)equlas和hashCode方法时应考虑的问题 +##重写(Override)equals和hashCode方法时应考虑的问题 ###理论上讲(编程语言、数学层面) equals() 定义了对象的相等关系(自反性、对称性、传递性)(有点抽象,更详细说明,请参考[javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) 。 From e4c99d754599845ec2d66f7b32684fce1fac02f8 Mon Sep 17 00:00:00 2001 From: lizeyang Date: 2016年5月23日 23:35:57 +0800 Subject: [PATCH 013/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 053f033..b8622db 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ + stackoverflow-Java-top-qa ======================= 对stackoverflow上Java相关、投票数TOP100的问答进行翻译,欢迎点star,我们会持续更新!!! 为了让"翻译"更有意义,给阅读者带来更多、更有效的收获,我们会有一些加工: 例如,对问题进行分类,整合多个答案、删除冗余内容、加上自己的验证结果、心得等等 - + 对于参与翻译的人,这也是很好的一个学习、理解过程,欢迎大家一起来翻译 ------------- @@ -72,6 +73,7 @@ stackoverflow-Java-top-qa * [我应该用哪一个@NotNull注解](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/which-notnull-java-annotation-should-i-use.md) * [怎样将堆栈追踪信息转换为字符串](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-convert-a-stack-trace-to-a-string.md) * [如何处理 java.lang.outOfMemoryError PermGen space error](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/dealing-with-java-lang-outofmemoryerror-permgen-space-error.md) +* [如何用0向左补齐一个整数](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) > 网络 @@ -83,6 +85,8 @@ stackoverflow-Java-top-qa * [LinkedList、ArrayList各自的使用场景,如何确认应该用哪一个呢?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/when-to-use-linkedlist-over-arraylist.md) * [StringBuilder和StringBuffer有哪些区别呢](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/stringbuilder-and-stringbuffer.md) * [为什么处理排序的数组要比非排序的快](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-processing-a-sorted-array-faster-than-an-unsorted-array.md) +* [如何使用Java创建一个内存泄漏的程序](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/creating-a-memory-leak-with-java.md) +* [为什么打印"B"会明显的比打印"#"慢](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-printing-b-dramatically-slower-than-printing.md) > 测试 @@ -96,8 +100,6 @@ stackoverflow-Java-top-qa ### 待翻译问题链接(还剩x问题) - [Why is subtracting these two times (in 1927) giving a strange result?](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result) - [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) -- [Creating a memory leak with Java [closed]](http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java) 用户AutumnLight正在翻译该问题 -- [Why is printing "B" dramatically slower than printing "#"?](http://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing) - [How can I create an executable jar with dependencies using Maven?](http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) - [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) From 6173090eefcb15f0306e3fbd50c22ad5067845e3 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年5月24日 00:00:10 +0800 Subject: [PATCH 014/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=9C=AA=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b8622db..dd5f68f 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ stackoverflow-Java-top-qa * [比较java枚举成员使用equal还是==](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/comparing-java-enum-members-or-equals.md) * [用java怎么创建一个文件并向该文件写文本内容](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-to-create-a-file-and-write-to-a-file-in-java.md) * [serialVersionUID 有什么作用?该如何使用?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md) +* [为什么Java的```Vector```类被认为是过时的或者废弃的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md) > 编程技巧 @@ -132,7 +133,6 @@ stackoverflow-Java-top-qa - [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) - [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) - [What's the difference between @Component, @Repository & @Service annotations in Spring?](http://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in) -- [Why is Java Vector class considered obsolete or deprecated?](http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated) - [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) - [Why does this go into an infinite loop?](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) - [When and how should I use a ThreadLocal variable?](http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable) From ee5bfae8ff741d99a39bfd01e99a5edd4355858d Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年5月24日 00:15:18 +0800 Subject: [PATCH 015/108] no message --- contents/avoiding-null-statements-in-java.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/contents/avoiding-null-statements-in-java.md b/contents/avoiding-null-statements-in-java.md index baf0f60..bff9a52 100644 --- a/contents/avoiding-null-statements-in-java.md +++ b/contents/avoiding-null-statements-in-java.md @@ -50,7 +50,8 @@ public interface Parser { 我们来改造一下 -类定义如下,这样定义findAction方法后,确保无论用户输入什么,都不会返回null对象 +类定义如下,这样定义findAction方法后,确保无论用户输入什么,都不会返回null对象: +```java public class MyParser implements Parser { private static Action DO_NOTHING = new Action() { public void doSomething() { /* do nothing */ } @@ -62,7 +63,7 @@ public class MyParser implements Parser { return DO_NOTHING; } }} - +``` 对比下面两份调用实例 1. 冗余: 每获取一个对象,就判一次空 @@ -90,11 +91,11 @@ ParserFactory.getParser().findAction(someInput).doSomething(); - 如果要用equal方法,请用object<不可能为空>.equal(object<可能为空>)) 例如: 使用 -"bar".equals(foo) +`"bar".equals(foo) ` 而不是 -foo.equals("bar") +`foo.equals("bar") ` - Java8或者guava lib中,提供了Optional类,这是一个元素容器,通过它来封装对象,可以减少判空。不过代码量还是不少。不爽。 - 如果你想返回null,请挺下来想一想,这个地方是否更应该抛出一个异常 stackoverflow链接: -http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab=votes#tab-top \ No newline at end of file +http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab=votes#tab-top From 7ab16f31a2d31aa9f14f7276a0caf7720cf1e917 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年5月25日 08:51:14 +0800 Subject: [PATCH 016/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../onvert-a-string-to-an-enum-in-java.md | 30 ------------------- 2 files changed, 1 insertion(+), 31 deletions(-) delete mode 100644 contents/onvert-a-string-to-an-enum-in-java.md diff --git a/README.md b/README.md index dd5f68f..9c8c7a9 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ stackoverflow-Java-top-qa * [用java怎么创建一个文件并向该文件写文本内容](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-to-create-a-file-and-write-to-a-file-in-java.md) * [serialVersionUID 有什么作用?该如何使用?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md) * [为什么Java的```Vector```类被认为是过时的或者废弃的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md) +* [Java的foreach循环是如何工作的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-does-the-java-for-each-loop-work.md) > 编程技巧 @@ -126,7 +127,6 @@ stackoverflow-Java-top-qa - [Setting multiple jars in java classpath](http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath) - [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) - [Is null check needed before calling instanceof](http://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof) -- [How does the Java for each loop work?](http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work) - [What is the Java equivalent for LINQ?](http://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) - [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) diff --git a/contents/onvert-a-string-to-an-enum-in-java.md b/contents/onvert-a-string-to-an-enum-in-java.md deleted file mode 100644 index 0e7fd5b..0000000 --- a/contents/onvert-a-string-to-an-enum-in-java.md +++ /dev/null @@ -1,30 +0,0 @@ -##在java中把String转换给enum类 -------------------------------------- - -###问题 -假设有有个枚举类: -```java -public enum Blah -{ - A, B, C, D -} -``` -现在我想把这个String转成枚举类,比如说"A"应该等于Blash.A.该怎么做? - ------- -###回答1 -```java -Blah A = Blah.valueOf("A"); -``` -这样传入"A"会返回Balsh枚举类. -###回答2 -```java -Blah A =Enum.valueOf(Blah.class, "A"); -``` -同样可以得到该枚举类 - -**这两个方法都会传入的参数大小写敏感,这个例子如果传入"a",则会报错No enum const class Blah.a.** - -stackoverflow原址: http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java - - From f0bc01868fc38caeba665b94691c69209ca8b782 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年5月25日 09:00:48 +0800 Subject: [PATCH 017/108] Merge branch 'master' of https://github.com/YuxiangQue/stackoverflow-java-top-qa into YuxiangQue-master # Conflicts: # contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md --- ...-pad-an-integers-with-zeros-on-the-left.md | 123 ++++++++++++++++-- ...-check-needed-before-calling-instanceof.md | 47 +++++++ 2 files changed, 161 insertions(+), 9 deletions(-) create mode 100644 contents/is-null-check-needed-before-calling-instanceof.md diff --git a/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md b/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md index 27809e0..4c632df 100644 --- a/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md +++ b/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md @@ -1,18 +1,123 @@ -# 如何用0向左补齐一个整数? +## 如何在整数左填充0 -## 问题 +### 问题 +如何在整数左填充0 +举例 1 = "0001" -在Java中如何把一个整数转化为字符串并且用0向左补齐呢? -我基本上是希望把一个不大于9999的整数用0补齐 (比如说1="0001")。 - -## 解答 +### 答案一,String.format String.format("%05d", yournumber); -可以将一个五位数用0补齐。 +用0填充,总长度为5 +https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html + +### 答案二,ApacheCommonsLanguage +如果需要在Java 1.5前使用,可以利用 Apache Commons Language 方法 + org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0') + +### 答案三,DecimalFormat + import java.text.DecimalFormat; + class TestingAndQualityAssuranceDepartment + { + public static void main(String [] args) + { + int x=1; + DecimalFormat df = new DecimalFormat("00"); + System.out.println(df.format(x)); + } + } + +### 答案四,自己实现 +如果效率很重要的话,相比于 String.format 函数的可以自己实现 + + /** + * @param in The integer value + * @param fill The number of digits to fill + * @return The given value left padded with the given number of digits + */ + public static String lPadZero(int in, int fill){ + + boolean negative = false; + int value, len = 0; + + if(in>= 0){ + value = in; + } else { + negative = true; + value = - in; + in = - in; + len ++; + } + + if(value == 0){ + len = 1; + } else{ + for(; value != 0; len ++){ + value /= 10; + } + } + + StringBuilder sb = new StringBuilder(); + + if(negative){ + sb.append('-'); + } + + for(int i = fill; i> len; i--){ + sb.append('0'); + } + + sb.append(in); + + return sb.toString(); + } + + 效率对比 + + public static void main(String[] args) { + Random rdm; + long start; + + // Using own function + rdm = new Random(0); + start = System.nanoTime(); + + for(int i = 10000000; i != 0; i--){ + lPadZero(rdm.nextInt(20000) - 10000, 4); + } + System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms"); + + // Using String.format + rdm = new Random(0); + start = System.nanoTime(); + + for(int i = 10000000; i != 0; i--){ + String.format("%04d", rdm.nextInt(20000) - 10000); + } + System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms"); + } + + 结果 + 自己的实现:1697ms + String.format:38134ms + +### 答案,Google Guava +Maven: + + + guava + com.google.guava + 14.0.1 + +样例: + + Strings.padStart("7", 3, '0') returns "007" + Strings.padStart("2020", 3, '0') returns "2020" +注意: +Guava 是非常有用的库,它提供了很多有用的功能,包括了Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus等 -https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html -Stackoverflow链接:http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left +stackoverflow原址: +http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left \ No newline at end of file diff --git a/contents/is-null-check-needed-before-calling-instanceof.md b/contents/is-null-check-needed-before-calling-instanceof.md new file mode 100644 index 0000000..d7a8008 --- /dev/null +++ b/contents/is-null-check-needed-before-calling-instanceof.md @@ -0,0 +1,47 @@ +## 在调用 instanceof 前需要进行null检查吗 + + +### 问题: + +null instanceof SomeClass 会返回 null 还是抛出 NullPointerException 异常 + +### 答案一 +在调用 instanceof 前不要进行null检查 +null instanceof SomeClass 会返回 null +在 Java Language Specification 中 http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2 + +``` +在运行时,如果该instanceof运算符的关系表达式(RelationExpression)不为 null,且这个引用可以被成功转型( §15.16),不抛出ClassCastException,则结果为true; + 否则结果为false。 +``` + +### 答案二 + public class IsInstanceOfTest { + + public static void main(final String[] args) { + + String s; + + s = ""; + + System.out.println((s instanceof String)); + System.out.println(String.class.isInstance(s)); + + s = null; + + System.out.println((s instanceof String)); + System.out.println(String.class.isInstance(s)); + } + } +打印出 + + true + true + false + false + +### 原文链接 +http://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof + + + \ No newline at end of file From a4adac54f2c7dcc18880359ecfebf49d8681dd4d Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年5月25日 09:02:53 +0800 Subject: [PATCH 018/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9c8c7a9..09ff925 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,8 @@ stackoverflow-Java-top-qa * [我应该用哪一个@NotNull注解](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/which-notnull-java-annotation-should-i-use.md) * [怎样将堆栈追踪信息转换为字符串](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-convert-a-stack-trace-to-a-string.md) * [如何处理 java.lang.outOfMemoryError PermGen space error](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/dealing-with-java-lang-outofmemoryerror-permgen-space-error.md) -* [如何用0向左补齐一个整数](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) +* [如何在整数左填充0](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) +* [在调用 instanceof 前需要进行null检查吗](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-null-check-needed-before-calling-instanceof.md) > 网络 @@ -126,7 +127,6 @@ stackoverflow-Java-top-qa - [Update Eclipse with Android development tools v. 23](http://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-v-23) - [Setting multiple jars in java classpath](http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath) - [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) -- [Is null check needed before calling instanceof](http://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof) - [What is the Java equivalent for LINQ?](http://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) - [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) From c4ef2b4bbbb92c92b4cfbc6220d9466f364df4eb Mon Sep 17 00:00:00 2001 From: severalfly Date: 2016年5月27日 18:08:02 +0800 Subject: [PATCH 019/108] Why is subtracting these two times (in 1927) giving a strange result? --- ...times-(in-1927)-giving-a-strange-result.md | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md diff --git a/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md b/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md new file mode 100644 index 0000000..d4f5d19 --- /dev/null +++ b/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md @@ -0,0 +1,80 @@ +## 为什么相减这两个时间(1927年)会得到奇怪的结果? + +### 问题 +如果运行下面的代码,我想要做的是解析两个相差1秒的日期字符串: +```java +public static void main(String[] args) throws ParseException { + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String str3 = "1927-12-31 23:54:07"; + String str4 = "1927-12-31 23:54:08"; + Date sDt3 = sf.parse(str3); + Date sDt4 = sf.parse(str4); + long ld3 = sDt3.getTime() /1000; + long ld4 = sDt4.getTime() /1000; + System.out.println(ld4-ld3); +} +``` +其结果是 +``` +353 +``` +为什么`ld4-ld3` 结果不是`1`(因为我期望得到1秒的时间差)而是`353`? + +如果我把两个日期都换成1秒后: +```java +String str3 = "1927-12-31 23:54:08"; +String str4 = "1927-12-31 23:54:09"; +``` +这样`ld4-ld3`就为`1`。 + +--- +java 版本 +``` +java version "1.6.0_22" +Java(TM) SE Runtime Environment (build 1.6.0_22-b04) +Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode) +``` +时区(`TimeZone.getDefault()`): +``` +sun.util.calendar.ZoneInfo[id="Asia/Shanghai", +offset=28800000,dstSavings=0, +useDaylight=false, +transitions=19, +lastRule=null] + +Locale(Locale.getDefault()): zh_CN +``` +## 回答 +这是12月31号上海时区切换的错误。 + +[这个页面](http://www.timeanddate.com/time/change/china/shanghai?year=1927)上有关于上海1927的详细说明。因为1927年末尾的午夜,时间回滚了5分52秒,所以"1927-12-31 23:54:08" 实际上发生了两次,并且很明显java解析立即得到了可能的后面一个,而忽略了其差别。 + +这在经常弄混且丰富的世界时区中还是一个插曲。 + +如果重新编译[TZDB](https://github.com/nodatime/nodatime/blob/master/src/NodaTime.Demo/StackOverflowExamples.cs#L68)的2013a版本,之前的问题就不再能解释类型行为。在2013a 的版本中,结果将是358秒,切换时间由23:54:03 变为23:54:08。 + +我能注意到这个都是因为我在[unit tests](https://github.com/nodatime/nodatime/blob/master/src/NodaTime.Demo/StackOverflowExamples.cs#L68)收集像Noda Time 这样的问题 + +这个测试现在已经被更新,但是也表明没有历史数据是安全的。 + +在TZDB 2014f中, 这个时间切换移动到了1900年12月31日,并且也被修改成唯一的343秒变化(如果你知道我在说啥的话,`t` 和 `t+1` 之间是343 秒)。 + +**更新** 为了回答[ Ken Kin's question](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result/6841479#comment22684267_6841479)的问题,看起来像是,对于任何在1900 UTC 之前的时间,java 在他们的标准时间中进行了简单的时区实现。 +```java +import java.util.TimeZone; + +public class Test { + public static void main(String[] args) throws Exception { + long startOf1900Utc = -2208988800000L; + for (String id : TimeZone.getAvailableIDs()) { + TimeZone zone = TimeZone.getTimeZone(id); + if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) { + System.out.println(id); + } + } + } +} +``` +上面的代码在我的windows 机器上没有任何输出,所以对于任何相对标准时间在1900年前且有偏移的时间,都会有时间过渡。TZDB 自己有数据回退到更早之前,并且不依赖任何修正过的标准时间(就是`getRawOffset`假设的有效的概念),所以其他库不再需要介绍这个切换。 + +stackoverflow[链接](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result) \ No newline at end of file From 4164f046402a4d77ceb4fbff6da51ef8965ef00b Mon Sep 17 00:00:00 2001 From: Yixiaohan <499065469@qq.com> Date: 2016年5月31日 15:09:09 +0800 Subject: [PATCH 020/108] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=8E=92=E7=89=88?= =?UTF-8?q?=E3=80=81=E4=BF=AE=E6=94=B9=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 代码排版、修改错别字 --- contents/avoiding-null-statements-in-java.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/contents/avoiding-null-statements-in-java.md b/contents/avoiding-null-statements-in-java.md index bff9a52..aab0bc7 100644 --- a/contents/avoiding-null-statements-in-java.md +++ b/contents/avoiding-null-statements-in-java.md @@ -75,7 +75,8 @@ if (parser == null) { } Action action = parser.findAction(someInput); if (action == null) { - // do nothing} else { + // do nothing} +else { action.doSomething();} ``` @@ -95,7 +96,7 @@ ParserFactory.getParser().findAction(someInput).doSomething(); 而不是 `foo.equals("bar") ` - Java8或者guava lib中,提供了Optional类,这是一个元素容器,通过它来封装对象,可以减少判空。不过代码量还是不少。不爽。 -- 如果你想返回null,请挺下来想一想,这个地方是否更应该抛出一个异常 +- 如果你想返回null,请停下来想一想,这个地方是否更应该抛出一个异常 stackoverflow链接: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab=votes#tab-top From 4b61f498ac933cbee79925320cf108ec740f12c0 Mon Sep 17 00:00:00 2001 From: unknown <陈恭帅> Date: Wed, 1 Jun 2016 15:49:35 +0800 Subject: [PATCH 021/108] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8F=90=E4=BA=A4?= =?UTF-8?q?=E7=A9=BA=E6=96=87=E4=BB=B6=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ion-shared-variables-and-multithreading.md | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md b/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md index e69de29..148ab53 100644 --- a/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md +++ b/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md @@ -0,0 +1,52 @@ +##How do servlets work? Instantiation, shared variables and multithreading +###问题: +假设,我有一个web服务器可以支持无数的servlets,对于通过这些servlets的信息,我正在获取这些servlets的上下文环境,并设置session变量。 +现在,如果有两个或者更多的user用户发送请求到这个服务器,session变量会发生什么变化?session对于所有的user是公共的还是不同的user拥有不同的session。如果用户彼此之间的session是不同的,那么服务器怎么区分辨别不同的用户呢? +另外一些相似的问题,如果有N个用户访问一个具体的servlets,那么这个servlets是只在第一个用户第一次访问的时候实例化,还是为每一个用户各自实例化呢? +###答案: +####ServletContext +当servletcontainer(像tomcat)启动的时候,它会部署和加载所有的webapplications,当一个webapplication加载完成后,servletcontainer就会创建一个ServletContext,并且保存在服务器的内存中。这个webapp的web.xml会被解析,web.xml中的每个```, and ```或者通过注解```@WebServlet, @WebFilter and @WebListener```,都会被创建一次并且也保存在服务器的内存中。对于所有filter,```init()```方法会被直接触发,当servletcontainer关闭的时候,它会unload所有的webapplications,触发所有实例化的servlets和filters的```destroy()```方法,最后,servletcontext和所有的servlets,filter和listener实例都会被销毁。 + +####HttpServletRequest and HttpServletResponse +servletcontainer 是附属于webserver的,而这个webserver会持续监听一个目标端口的```HTTP request```请求,这个端口在开发中经常会被设置成8080,而在生产环境会被设置成80。当一个客户端(比如用户的浏览器)发送一个HTTP request,servletcontainer就会创建新的HttpServletRequest对象和HttpServletResponse对象。。。。 + +在有filter的情况下,```doFilter()```方法会被触发。当代码调用```chain.doFilter(request, response)```时候,请求会经过下一个过滤器filter,如果没有了过滤器,会到达servlet。在servlets的情况下,```service()```触发,然后根据```request.getMethod()```确定执行doGet()还是```doPost()```,如果当前servlet找不到请求的方法,返回405error。 + +request对象提供了HTTP请求所有的信息,比如request headers和request body,response对象提供了控制和发送HTTP响应的的能力,并且以你想要的方式,比如设置headers和body。当HTTP响应结束,请求和响应对象会被销毁(实际上,大多数container将会清洗到这些对象的状态然后回收这些事例以重新利用) +####httpSession +当客户端第一次访问webapp或者通过```request.getSession()```方法第一次获取httpSession +,servletcontainer 将会创建一个新的HttpSession 对象,产生一个长的唯一的ID标记session(可以通过session.getId()),并且将这个session存储在server内存中。servletcontainer 同时会在HTTP response的Header中设置```Set-Cookie```cookie值,其中cookie name为JSESSIONID,cookie value为唯一的长ID值。 + +在接下来的连续请求中,客户端浏览器都要cookie通过header带回,然后servletcontainer 会根据cookie中的JSESSIONID 值,获得server内存中的对应的httpSession。 + +只要没超过``````设定的值,httpSession对象会一直存在,``````大小可以在web.xml中设定,默认是30分钟。所以如果连续30分钟之内客户端不再访问webapp,servletcontainer就会销毁对应的session。接下来的request请求即使cookies依旧存在,但是却不再有对应的session了。servletcontainer 会创建新的session。 + +另外一方面,session cookie在浏览器端有默认的生命时长,就是只要浏览器一直在运行,所以当浏览器关闭,浏览器端的cookie会被销毁。 +####最后 +- 只要webapp存在,ServletContext 一定会存在。并且ServletContext 是被所有session和request共享的。 +- 只要客户端用同一个浏览器和webapp交互并且该session没有在服务端超时,HttpSession 就会一直存在。并且在同一个会话中所有请求都是共享的。 +- 只有当完整的response响应到达,HttpServletRequest 和 HttpServletResponse才不再存活,并且不被共享。 +- 只要webapp存在,servlet、filter和listener就会存在。他们被所有请求和会话共享。 +- 只要问题中的对象存在,任何设置在ServletContext, HttpServletRequest 和 HttpSession中的属性就会存在。 + +####线程安全 +就是说,你主要关注的是线程安全性。你应该了解到,servlets和filter是被所有请求共享的。这正是Java的美妙之处,它的多线程和不同的线程可以充分利用同样的实例instance,否则对于每一个request请求都要重复创建和调用init()和destroy()开销太大。 + +但是你也应该注意到,你不应该把任何请求或会话作用域的数据作为一个servlet或过滤器的实例变量。这样会被其他会话的请求共享,并且那是线程不安全的!下面的例子阐明的这点: +``` +public class ExampleServlet extends HttpServlet { + + private Object thisIsNOTThreadSafe; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + Object thisIsThreadSafe; + + thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests! + thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe. + } +} +``` + +stackoverflow链接: + +http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-shared-variables-and-multithreading \ No newline at end of file From 94d69915d0b30d39908628b110e033a011941784 Mon Sep 17 00:00:00 2001 From: ArronDon Date: Wed, 1 Jun 2016 22:19:44 +0800 Subject: [PATCH 022/108] when-and-how-should-i-use-a-threadlocal-variable --- ...how-should-i-use-a-threadlocal-variable.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 contents/when-and-how-should-i-use-a-threadlocal-variable.md diff --git a/contents/when-and-how-should-i-use-a-threadlocal-variable.md b/contents/when-and-how-should-i-use-a-threadlocal-variable.md new file mode 100644 index 0000000..17cb54c --- /dev/null +++ b/contents/when-and-how-should-i-use-a-threadlocal-variable.md @@ -0,0 +1,33 @@ +## 该什么使用 ThreadLocal变量,它是如何工作的? +### 回答1 +一种可能的(也是常见的)使用情形是你不想通过同步方式(synchronized)访问非线程安全的对象(说的就是SimpleDateFormat),而是想给每个线程一个对象实例的时候。 +例如 +````java +public class Foo +{ + // SimpleDateFormat is not thread-safe, so give one to each thread + private static final ThreadLocal formatter = new ThreadLocal(){ + @Override + protected SimpleDateFormat initialValue() + { + return new SimpleDateFormat("yyyyMMdd HHmm"); + } + }; + + public String formatIt(Date date) + { + return formatter.get().format(date); + } +} +```` +### 回答2 +因为ThreadLocal是一个既定线程内部的数据引用,你可能在使用线程池的应用服务器上因此引起类加载时候的内存泄漏。你需要使用remove()方法很小心地清理TheadLocal中get()或者set()的变量。 +如果程序执行完毕没有清理的话,它持有的任何对类的引用将作为部署的Web应用程序的一部分仍保持在永久堆,永远无法得到回收。重新部署/取消部署也无法清理对应用程序类的引用,因为线程不是被你的应用程序所拥有的。 +每次成功部署都会创建一个永远不会被垃圾回收类的实例。 + +最后将会遇到内存不足的异常-java.lang.java.lang.OutOfMemoryError: PermGen space -XX:MaxPermSize,在google了很多答案之后你可能只是增加了-XX:MaxPermSize,而不是修复这个bug。 +倘若你的确遇到这种问题,可以通过[Eclipse's Memory Analyzer](http://www.eclipse.org/mat/)或根据[Frank Kieviet's guide](https://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java) 和 [followup](https://blogs.oracle.com/fkieviet/entry/how_to_fix_the_dreaded)来判断哪些线程和类保留了那些引用。 + +更新:又发现了[Alex Vasseur's blog entry](http://avasseur.blogspot.jp/2003/11/threadlocal-and-memory-leaks.html),它帮助我查清楚了一些ThreadLocal的问题。 + +stackoverflow链接:http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable From 36c07fc5a2d329c267bdfaec28ec091a331ffc02 Mon Sep 17 00:00:00 2001 From: ArronDon Date: Wed, 1 Jun 2016 22:22:24 +0800 Subject: [PATCH 023/108] Update when-and-how-should-i-use-a-threadlocal-variable.md --- contents/when-and-how-should-i-use-a-threadlocal-variable.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/when-and-how-should-i-use-a-threadlocal-variable.md b/contents/when-and-how-should-i-use-a-threadlocal-variable.md index 17cb54c..50d97ef 100644 --- a/contents/when-and-how-should-i-use-a-threadlocal-variable.md +++ b/contents/when-and-how-should-i-use-a-threadlocal-variable.md @@ -1,4 +1,4 @@ -## 该什么使用 ThreadLocal变量,它是如何工作的? +## 该什么时候使用 ThreadLocal变量,它是如何工作的? ### 回答1 一种可能的(也是常见的)使用情形是你不想通过同步方式(synchronized)访问非线程安全的对象(说的就是SimpleDateFormat),而是想给每个线程一个对象实例的时候。 例如 From 500ee1d61a5ed2038f4c8a913e9328a0266fe75d Mon Sep 17 00:00:00 2001 From: MagicWolf Date: 2016年6月30日 14:27:53 +0800 Subject: [PATCH 024/108] =?UTF-8?q?=E7=BF=BB=E8=AF=91Convert=20a=20String?= =?UTF-8?q?=20to=20an=20enum=20in=20Java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/lookup-enum-by-string-value.md | 106 ++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 contents/lookup-enum-by-string-value.md diff --git a/contents/lookup-enum-by-string-value.md b/contents/lookup-enum-by-string-value.md new file mode 100644 index 0000000..2bb583c --- /dev/null +++ b/contents/lookup-enum-by-string-value.md @@ -0,0 +1,106 @@ +## Java 中如何将 String 转换为 enum + +###问题 +我有一个 enum 类 + +``` java +public enum Blah { + A, B, C, D +} +``` +我想要找到一个 `String` 对应的 enum 值。例如, `"A"` 将是 `Blah.A`.如何做到? + +我需要使用 `Enum.valueOf()` 方法吗? 如果是该如何使用? + +--- + +### A1 + +是的, `Blah.valueOf("A")` 将会给你 `Blah.A`. + +静态方法 `valueof()` 和 `values()` 在编译时期被插入,并不存在于源码中。但是在Javadoc中;例如,[`Dialog.ModalityType`](http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html "Dialog.ModalityType")中显示了这两个方法。 + + +### A2 + +另一个解答,如果文本和 `enumeration` 值不一致 + +``` java +public enum Blah { + A("text1"), + B("text2"), + C("text3"), + D("text4"); + + private String text; + + Blah(String text) { + this.text = text; + } + + public String getText() { + return this.text; + } + + public static Blah fromString(String text) { + if (text != null) { + for (Blah b : Blah.values()) { + if (text.equalsIgnoreCase(b.text)) { + return b; + } + } + } + return null; + } +} +``` +_评论区在讨论是应该返回null还是抛出异常,个人认为视具体情况,允许转换失败就返回null,不允许就抛出异常,或许创建一个特殊的空对象是个好的选择 -译者注_ + +### A3 + +这是我使用的一个工具类: + +``` java +/** + * 一个对于所有Enum类通用的方法,因为他们不能有另一个基类 + * @param Enum type + * @param c enum type. All enums must be all caps. + * @param string case insensitive + * @return corresponding enum, or null + */ +public static > T getEnumFromString(Class c, String string) { + if( c != null && string != null ) { + try { + return Enum.valueOf(c, string.trim().toUpperCase()); + } catch(IllegalArgumentException ex) { + } + } + return null; +} +``` +之后,在我的enum类中通常如此使用来减少打字: +``` java +public static MyEnum fromString(String name) { + return getEnumFromString(MyEnum.class, name); +} +``` +如果的enums不是全部大写,只需要修改 `Enum.valueOf` 这一行。 +很遗憾,我不能使用 `T.class` 传给 `Enum.valueOf`,因为 `T`会被擦出。 + +_评论区对于答主的异常处理一片指责 -译者注_ + +###A4 +如果你不想编写自己的工具类,可以使用 Google的 `guava` 库: +``` java +Enums.getIfPresent(Blah.class, "A") +``` +它让你检查是否 `Blan`中存在 `A`并且不抛出异常 + +_完整方法签名 `Optional getIfPresent(Class enumClass, String value)` , `Optional` 对象可以优雅的解决null值问题 -译者注_ + +--- +_其他的答案都大同小异,感兴趣的可以看原帖_ +_原帖:[Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/lookup-enum-by-string-value)_ +_译者:[MagicWolf](https://github.com/DaiDongLiang)_ + + From cc2ca4ac2927a762b8b08c0015c9c5cd1c3c21d3 Mon Sep 17 00:00:00 2001 From: gaoshihang <472024406@qq.com> Date: 2016年7月25日 15:05:02 +0800 Subject: [PATCH 025/108] Create why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这是我翻译的why-is-subtracting-these-two-times-in-1927-giving-a-strange-result这篇问答的中文版。 --- ...o-times-in-1927-giving-a-strange-result.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md diff --git a/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md b/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md new file mode 100644 index 0000000..d2f4449 --- /dev/null +++ b/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md @@ -0,0 +1,59 @@ +##为什么这两个时间(1927年)相减会得到一个奇怪的结果? + +###问题描述 +如果我运行如下的程序,将两个相距一秒的日期解析成字符串并比较他们。 +``` +public static void main(String[] args) throws ParseException { + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String str3 = "1927-12-31 23:54:07"; + String str4 = "1927-12-31 23:54:08"; + Date sDt3 = sf.parse(str3); + Date sDt4 = sf.parse(str4); + long ld3 = sDt3.getTime() /1000; + long ld4 = sDt4.getTime() /1000; + System.out.println(ld4-ld3); +} +``` + +输出结果为: +``` +353 +``` + +为什么`ld4-ld3`不是`1`(正如我所期望的那样),而是`353`? + +如果我把时间改变为之后的一秒: +``` +String str3 = "1927-12-31 23:54:08"; +String str4 = "1927-12-31 23:54:09"; +``` + +这时,`ld4-ld3`的结果为`1`. + +java版本: +``` +java version "1.6.0_22" +Java(TM) SE Runtime Environment (build 1.6.0_22-b04) +Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode) +``` + +时区: +``` +sun.util.calendar.ZoneInfo[id="Asia/Shanghai", +offset=28800000,dstSavings=0, +useDaylight=false, +transitions=19, +lastRule=null] + +Locale(Locale.getDefault()): zh_CN +``` + +###问题回答 +这是因为1927年11月31日上海的时区改变了。 +观看[此页](http://www.timeanddate.com/time/change/china/shanghai?year=1927)获得更多关于上海1927年的细节。 +这个问题主要是由于在1927年12月31日的午夜,时钟回调了5分钟零52秒。 +所以"1927-12-31 23:54:08"这个时间实际上发生了两次,看上去java将这个时间解析为之后的那个瞬间。 +因此出现了这种差别。 + +这只是美好但奇怪的世界时区中的一个插曲。 + From bbe5225c9b0cb85f2705bd560e48587e54f312ad Mon Sep 17 00:00:00 2001 From: gaoshihang <472024406@qq.com> Date: 2016年7月25日 15:16:25 +0800 Subject: [PATCH 026/108] Update why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md --- ...ubtracting-these-two-times-in-1927-giving-a-strange-result.md | 1 + 1 file changed, 1 insertion(+) diff --git a/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md b/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md index d2f4449..d436087 100644 --- a/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md +++ b/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md @@ -57,3 +57,4 @@ Locale(Locale.getDefault()): zh_CN 这只是美好但奇怪的世界时区中的一个插曲。 +stackoverflow链接:[Why is subtracting these two times (in 1927) giving a strange result?](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result) From a914c65177afe26a52b76a91537abb9b67039ca1 Mon Sep 17 00:00:00 2001 From: yu Date: Tue, 2 Aug 2016 14:34:54 +0800 Subject: [PATCH 027/108] owen1190 --- contents/lookup-enum-by-string-value.md | 54 +++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 contents/lookup-enum-by-string-value.md diff --git a/contents/lookup-enum-by-string-value.md b/contents/lookup-enum-by-string-value.md new file mode 100644 index 0000000..848010d --- /dev/null +++ b/contents/lookup-enum-by-string-value.md @@ -0,0 +1,54 @@ +#通过String值查找enum中常量 +## 问题 +假设有一个枚举值 + public enum Blah + { + A,B,C,D + } +想通过一个String类型,找到所需要的枚举值。 +例如"A"->Blah.A +是使用Enum.valueOf()方法吗?该如何使用 +## 回答 +Blah.valueOf("A")会得到Blah.A +虽然api文档确实有静态方法valueOf()和values(),但是二者在编译期时才出现,而且在没出现在源程序中。 +例如可以采用Dialog.ModalityType显示了两种方法来处理这种情况。 +备注:Blah.valueOf("A")的方法是区分大小写,且不能含有空格。 + +如果String值与enum中不相同的查找方法: + + public enum Blah + { + A("text1"), + B("text2"), + C("text3"), + D("text4"); + private String text; + Blah(String text) + { + this.text = text; + } + public String getText() + { + return this.text; + } + + public static Blah fromString(String text) + { + if (text != null) + { + for (Blah b : Blah.values()) + { + if (text.equalsIgnoreCase(b.text)) + { + return b; + } + } + } + return null; + } + } + +备注:throw new IllegalArgumentException("No constant with text"+text+"found")会比直接抛出null更好 + +原文链接: +> http://stackoverflow.com/questions/604424/lookup-enum-by-string-value# \ No newline at end of file From 7c7b598cb004ff85f5c93e8c8735309ea4a878cc Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: Wed, 3 Aug 2016 00:11:16 +0800 Subject: [PATCH 028/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 09ff925..0295a5e 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ stackoverflow-Java-top-qa * [serialVersionUID 有什么作用?该如何使用?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md) * [为什么Java的```Vector```类被认为是过时的或者废弃的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md) * [Java的foreach循环是如何工作的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-does-the-java-for-each-loop-work.md) +* [为什么相减这两个时间(1927年)会得到奇怪的结果](/contens/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md) > 编程技巧 @@ -101,7 +102,6 @@ stackoverflow-Java-top-qa * [如何获取Android设备唯一ID](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-there-a-unique-android-device-id.md) ### 待翻译问题链接(还剩x问题) -- [Why is subtracting these two times (in 1927) giving a strange result?](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result) - [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) - [How can I create an executable jar with dependencies using Maven?](http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) From 0c8be56af7fcd1d0180215eacc2e09bcf89678fe Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: Wed, 3 Aug 2016 00:23:47 +0800 Subject: [PATCH 029/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0295a5e..f42e967 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,10 @@ stackoverflow-Java-top-qa * [serialVersionUID 有什么作用?该如何使用?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md) * [为什么Java的```Vector```类被认为是过时的或者废弃的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md) * [Java的foreach循环是如何工作的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-does-the-java-for-each-loop-work.md) -* [为什么相减这两个时间(1927年)会得到奇怪的结果](/contens/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md) +* [为什么相减这两个时间(1927年)会得到奇怪的结果](/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md) +* [Java 中如何将 String 转换为 enum](/contents/lookup-enum-by-string-value.md) +* [该什么时候使用 ThreadLocal变量,它是如何工作的](/contents/when-and-how-should-i-use-a-threadlocal-variable.md) +* [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) > 编程技巧 @@ -118,7 +121,6 @@ stackoverflow-Java-top-qa - [How do you assert that a certain exception is thrown in JUnit 4 tests?](http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests) - [What exactly is Apache Camel?](http://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel) - [How can I permanently have line numbers in IntelliJ?](http://stackoverflow.com/questions/13751/how-can-i-permanently-have-line-numbers-in-intellij) -- [How do servlets work? Instantiation, shared variables and multithreading](http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-shared-variables-and-multithreading) - [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) - [How do I discover memory usage of my application in Android?](http://stackoverflow.com/questions/2298208/how-do-i-discover-memory-usage-of-my-application-in-android) - [How can I generate an MD5 hash?](http://stackoverflow.com/questions/415953/how-can-i-generate-an-md5-hash) @@ -129,13 +131,11 @@ stackoverflow-Java-top-qa - [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) - [What is the Java equivalent for LINQ?](http://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) -- [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) - [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) - [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) - [What's the difference between @Component, @Repository & @Service annotations in Spring?](http://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in) - [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) - [Why does this go into an infinite loop?](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) -- [When and how should I use a ThreadLocal variable?](http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable) - [decompiling DEX into Java sourcecode](http://stackoverflow.com/questions/1249973/decompiling-dex-into-java-sourcecode) - [How to create a generic array in Java?](http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) - [Why does Math.round(0.49999999999999994) return 1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) From dd26ebd6525b18251d891ef32c4e3fd45273296b Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: Wed, 3 Aug 2016 00:30:20 +0800 Subject: [PATCH 030/108] Merge branch 'master' of https://github.com/andysim3d/stackoverflow-java-top-qa into andysim3d-master # Conflicts: # contents/lookup-enum-by-string-value.md --- contents/how-can-i-generate-an-md5-hash.md | 25 ++++++++++++++++++++++ contents/lookup-enum-by-string-value.md | 6 +++--- 2 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 contents/how-can-i-generate-an-md5-hash.md diff --git a/contents/how-can-i-generate-an-md5-hash.md b/contents/how-can-i-generate-an-md5-hash.md new file mode 100644 index 0000000..b122024 --- /dev/null +++ b/contents/how-can-i-generate-an-md5-hash.md @@ -0,0 +1,25 @@ +##如何计算MD5值 + +###问题 +Java中有没有方法可以计算一个String的MD5值? + + +###回答 +你可以用 ```MessageDigest``` 的MD5实例来计算String的MD5值。 + +使用 ```MessageDigest``` 和 String 时,一定要显式声明你的数据编码类型。如果你使用无参的 ```String.getBytes()``` , 它会以当前平台的默认编码来转换数据。不同平台的默认编码可能是不同的,这可能会导致你的数据不一致。 + +``` java +import java.security.*; + +.. + +byte[] bytesOfMessage = yourString.getBytes("UTF-8"); +MessageDigest md = MessageDigest.getInstance("MD5"); +byte[] thedigest = md.digest(bytesOfMessage); +``` + +如果你的要计算的数据量很大,你可以循环使用 ```.update(byte[])``` 方法来加载数据。加载完毕后用 ```.digest()``` 方法来得到计算出的MD5值。 + +stackoverflow链接 +http://stackoverflow.com/questions/415953/how-can-i-generate-an-md5-hash diff --git a/contents/lookup-enum-by-string-value.md b/contents/lookup-enum-by-string-value.md index 2bb583c..99f83c4 100644 --- a/contents/lookup-enum-by-string-value.md +++ b/contents/lookup-enum-by-string-value.md @@ -83,7 +83,7 @@ public static > T getEnumFromString(Class c, String string) public static MyEnum fromString(String name) { return getEnumFromString(MyEnum.class, name); } -``` +``` 如果的enums不是全部大写,只需要修改 `Enum.valueOf` 这一行。 很遗憾,我不能使用 `T.class` 传给 `Enum.valueOf`,因为 `T`会被擦出。 @@ -100,7 +100,7 @@ _完整方法签名 `Optional getIfPresent(Class enumClass, String value)` --- _其他的答案都大同小异,感兴趣的可以看原帖_ -_原帖:[Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/lookup-enum-by-string-value)_ +stackoverflow链接 +http://stackoverflow.com/questions/604424/lookup-enum-by-string-value _译者:[MagicWolf](https://github.com/DaiDongLiang)_ - From 9eafdcb795657dc097db0206730162a5908aba69 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: Wed, 3 Aug 2016 00:32:58 +0800 Subject: [PATCH 031/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f42e967..b464834 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ stackoverflow-Java-top-qa * [Java 中如何将 String 转换为 enum](/contents/lookup-enum-by-string-value.md) * [该什么时候使用 ThreadLocal变量,它是如何工作的](/contents/when-and-how-should-i-use-a-threadlocal-variable.md) * [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) +* [如何计算MD5值](/contents/how-can-i-generate-an-md5-hash.md) > 编程技巧 @@ -123,7 +124,6 @@ stackoverflow-Java-top-qa - [How can I permanently have line numbers in IntelliJ?](http://stackoverflow.com/questions/13751/how-can-i-permanently-have-line-numbers-in-intellij) - [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) - [How do I discover memory usage of my application in Android?](http://stackoverflow.com/questions/2298208/how-do-i-discover-memory-usage-of-my-application-in-android) -- [How can I generate an MD5 hash?](http://stackoverflow.com/questions/415953/how-can-i-generate-an-md5-hash) - [Uncatchable ChuckNorrisException](http://stackoverflow.com/questions/13883166/uncatchable-chucknorrisexception) - [Can I add jars to maven 2 build classpath without installing them?](http://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them) - [Update Eclipse with Android development tools v. 23](http://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-v-23) From b609912a2723beeea947ce0001870c1d742dd70f Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: Wed, 3 Aug 2016 00:36:29 +0800 Subject: [PATCH 032/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- ...times-(in-1927)-giving-a-strange-result.md | 80 ------------------- 2 files changed, 1 insertion(+), 81 deletions(-) delete mode 100644 contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md diff --git a/README.md b/README.md index b464834..e672a6b 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ stackoverflow-Java-top-qa * [serialVersionUID 有什么作用?该如何使用?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/what-is-a-serialversionuid-and-why-should-i-use-it.md) * [为什么Java的```Vector```类被认为是过时的或者废弃的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md) * [Java的foreach循环是如何工作的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-does-the-java-for-each-loop-work.md) -* [为什么相减这两个时间(1927年)会得到奇怪的结果](/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md) +* [为什么相减这两个时间(1927年)会得到奇怪的结果](/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md) * [Java 中如何将 String 转换为 enum](/contents/lookup-enum-by-string-value.md) * [该什么时候使用 ThreadLocal变量,它是如何工作的](/contents/when-and-how-should-i-use-a-threadlocal-variable.md) * [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) diff --git a/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md b/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md deleted file mode 100644 index d4f5d19..0000000 --- a/contents/why-is-subtracting-these-two-times-(in-1927)-giving-a-strange-result.md +++ /dev/null @@ -1,80 +0,0 @@ -## 为什么相减这两个时间(1927年)会得到奇怪的结果? - -### 问题 -如果运行下面的代码,我想要做的是解析两个相差1秒的日期字符串: -```java -public static void main(String[] args) throws ParseException { - SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String str3 = "1927-12-31 23:54:07"; - String str4 = "1927-12-31 23:54:08"; - Date sDt3 = sf.parse(str3); - Date sDt4 = sf.parse(str4); - long ld3 = sDt3.getTime() /1000; - long ld4 = sDt4.getTime() /1000; - System.out.println(ld4-ld3); -} -``` -其结果是 -``` -353 -``` -为什么`ld4-ld3` 结果不是`1`(因为我期望得到1秒的时间差)而是`353`? - -如果我把两个日期都换成1秒后: -```java -String str3 = "1927-12-31 23:54:08"; -String str4 = "1927-12-31 23:54:09"; -``` -这样`ld4-ld3`就为`1`。 - ---- -java 版本 -``` -java version "1.6.0_22" -Java(TM) SE Runtime Environment (build 1.6.0_22-b04) -Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode) -``` -时区(`TimeZone.getDefault()`): -``` -sun.util.calendar.ZoneInfo[id="Asia/Shanghai", -offset=28800000,dstSavings=0, -useDaylight=false, -transitions=19, -lastRule=null] - -Locale(Locale.getDefault()): zh_CN -``` -## 回答 -这是12月31号上海时区切换的错误。 - -[这个页面](http://www.timeanddate.com/time/change/china/shanghai?year=1927)上有关于上海1927的详细说明。因为1927年末尾的午夜,时间回滚了5分52秒,所以"1927-12-31 23:54:08" 实际上发生了两次,并且很明显java解析立即得到了可能的后面一个,而忽略了其差别。 - -这在经常弄混且丰富的世界时区中还是一个插曲。 - -如果重新编译[TZDB](https://github.com/nodatime/nodatime/blob/master/src/NodaTime.Demo/StackOverflowExamples.cs#L68)的2013a版本,之前的问题就不再能解释类型行为。在2013a 的版本中,结果将是358秒,切换时间由23:54:03 变为23:54:08。 - -我能注意到这个都是因为我在[unit tests](https://github.com/nodatime/nodatime/blob/master/src/NodaTime.Demo/StackOverflowExamples.cs#L68)收集像Noda Time 这样的问题 - -这个测试现在已经被更新,但是也表明没有历史数据是安全的。 - -在TZDB 2014f中, 这个时间切换移动到了1900年12月31日,并且也被修改成唯一的343秒变化(如果你知道我在说啥的话,`t` 和 `t+1` 之间是343 秒)。 - -**更新** 为了回答[ Ken Kin's question](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result/6841479#comment22684267_6841479)的问题,看起来像是,对于任何在1900 UTC 之前的时间,java 在他们的标准时间中进行了简单的时区实现。 -```java -import java.util.TimeZone; - -public class Test { - public static void main(String[] args) throws Exception { - long startOf1900Utc = -2208988800000L; - for (String id : TimeZone.getAvailableIDs()) { - TimeZone zone = TimeZone.getTimeZone(id); - if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) { - System.out.println(id); - } - } - } -} -``` -上面的代码在我的windows 机器上没有任何输出,所以对于任何相对标准时间在1900年前且有偏移的时间,都会有时间过渡。TZDB 自己有数据回退到更早之前,并且不依赖任何修正过的标准时间(就是`getRawOffset`假设的有效的概念),所以其他库不再需要介绍这个切换。 - -stackoverflow[链接](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result) \ No newline at end of file From 2d7c9a047e2d2b9de5c73309ae1c201f2ffb2483 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: Wed, 3 Aug 2016 09:16:03 +0800 Subject: [PATCH 033/108] =?UTF-8?q?=E6=B7=BB=E5=8A=A0gitbook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SUMMARY.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 SUMMARY.md diff --git a/SUMMARY.md b/SUMMARY.md new file mode 100644 index 0000000..9f8edf2 --- /dev/null +++ b/SUMMARY.md @@ -0,0 +1 @@ +\# Summary* [前言](README.md) \ No newline at end of file From 465351b8be23f2cb294a5adc1ea62e803a002269 Mon Sep 17 00:00:00 2001 From: andysim3d Date: Thu, 4 Aug 2016 14:55:05 -0400 Subject: [PATCH 034/108] translate how-do-i-create-a-java-string-from-the-contents-of-a-file --- ...java-string-from-the-contents-of-a-file.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md diff --git a/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md b/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md new file mode 100644 index 0000000..0345f21 --- /dev/null +++ b/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md @@ -0,0 +1,53 @@ +##如何从文件里读取字符串 + +###从文件里读取所有文本: + +代码: +```java +static String readFile(String path, Charset encoding) + throws IOException +{ + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded, encoding); +} + +``` + +###一行一行读入文本: + +Java 7 提供了一个方便的方法可以直接将文件中的文本一行一行读入,存放在一个List容器里。 +```JAVA +List lines = Files.readAllLines(Paths.get(path), encoding); +``` + +###内存使用率 + +第一个方法,一次读取所有文本的方法,占用内存较多,因为它一次性保留了文件的所有原始信息,包括换行符之类的"无用"字符。 + +第二个方法,按行读入,比起一次性全部读入,要消耗更少的内存。因为它每次只将一行的文件信息放在缓存中。然而,如果文本文件很大,这种方法依然会占用很多内存。 + +如果你的程序需要处理很大的文本文件,在设计的时候就要考虑,分配一块固定的缓存,每次从流中读入文件的一部分放入缓存,处理,然后清空缓存,把下一部分读入缓存,直道处理完所有的数据。 + +这里的"很大"是相对于计算机性能的。一般来说,几十个G的文件应当算是大文件。 + +###字符编码 + +还有一件事需要注意,就是字符编码。不同的平台有自己的默认编码,所以有时候你的程序需要指定编码,来保持平台无关/跨平台。 + +```StandardCharsets``` 类定义了常用的编码类型,你可以用如下方法调用: + +```java +String content = readFile("test.txt", StandardCharsets.UTF_8); +``` + +可以通过```Charset```类来获得平台默认的字符编码。 + +```java +String content = readFile("test.txt", Charset.defaultCharset()); +``` + +注: 这个答案与之前Java6版本时的答案完全不同。Java 7 新增的工具类极大的优化了字符处理,文件读取等功能。Java 6 常用的内存映射方法已不适合在Java 7 以后的版本使用。 + + + + From b11f01e43ed840a49daac64aea146969c426a854 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 4 Aug 2016 14:57:00 -0400 Subject: [PATCH 035/108] Update how-do-i-create-a-java-string-from-the-contents-of-a-file.md --- ...how-do-i-create-a-java-string-from-the-contents-of-a-file.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md b/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md index 0345f21..323fdeb 100644 --- a/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md +++ b/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md @@ -26,7 +26,7 @@ List lines = Files.readAllLines(Paths.get(path), encoding); 第二个方法,按行读入,比起一次性全部读入,要消耗更少的内存。因为它每次只将一行的文件信息放在缓存中。然而,如果文本文件很大,这种方法依然会占用很多内存。 -如果你的程序需要处理很大的文本文件,在设计的时候就要考虑,分配一块固定的缓存,每次从流中读入文件的一部分放入缓存,处理,然后清空缓存,把下一部分读入缓存,直道处理完所有的数据。 +如果你的程序需要处理很大的文本文件,在设计的时候就要考虑,分配一块固定的缓存,每次从流中读入文件的一部分放入缓存,处理,然后清空缓存,把下一部分读入缓存,直到处理完所有的数据。 这里的"很大"是相对于计算机性能的。一般来说,几十个G的文件应当算是大文件。 From 1eeda60ec3fbeaeb2548d60b4969fef376655f82 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 4 Aug 2016 14:58:53 -0400 Subject: [PATCH 036/108] Update how-do-i-create-a-java-string-from-the-contents-of-a-file.md --- ...w-do-i-create-a-java-string-from-the-contents-of-a-file.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md b/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md index 323fdeb..1dc835b 100644 --- a/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md +++ b/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md @@ -48,6 +48,8 @@ String content = readFile("test.txt", Charset.defaultCharset()); 注: 这个答案与之前Java6版本时的答案完全不同。Java 7 新增的工具类极大的优化了字符处理,文件读取等功能。Java 6 常用的内存映射方法已不适合在Java 7 以后的版本使用。 - +### 原文链接 +http://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file + From e719facf644847a17a925122a39c96a255850b09 Mon Sep 17 00:00:00 2001 From: yu Date: Fri, 5 Aug 2016 11:04:24 +0800 Subject: [PATCH 037/108] what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java --- ...-reference-and-a-weak-reference-in-java.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md diff --git a/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md b/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md new file mode 100644 index 0000000..eb01281 --- /dev/null +++ b/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md @@ -0,0 +1,38 @@ +# Java中软引用和弱引用的区别 +## 问题 +题目就是问题 + +## 解答 +### 回答1 +从Ethan Nicholas的《Understanding Weak References》中 + +弱引用: +放置一个弱引用的作用,不是强有力强制一个对象保存在内存中。弱引用允许利用垃圾收集者的能力去决定可达性,所以你不需要自己做,你只需要创建一个软引用: + + WeakReference weakWidgt = new WeakReference(widgt); + +然后在代码别的地方你可以使用 `weakWidget.get()` 来获取真实的 `Widgt` 对象,当然弱引用足以强大能抵制垃圾收集器,所以你也许发现(如果没有强引用指向widget)`weakWidget.get()`突然开始返回null + +软引用 + +软引用就像弱引用一样,除了它不会着急将引用的对象扔出去。只有弱可达性的对象(这样的对象最强的引用只能是弱引用)将在下一次垃圾收集处理中被抛弃,但是软可达性的对象通常可以坚持一会。 + +软引用不要求与弱引用有什么不同,但是实际中,只要内存足够,软可达的对象通常会维持下去。对于缓存来说,这是个不错的基础,就像以上图像缓存描述,虽然可以让垃圾收集者担心对象是如何可达(一个强可达性的对象从不会从缓存中移除)和她们需要消耗多少内存 + +而且Peter Kessler备注到 + +Sun JRE 对待软引用和弱引用是不同的。如果内存是够用的。我们应坚持用软引用引用对象。一个细节是:对于客户端和服务器,JRE的政策是不同的:客户端,JRE试图保持通过清除软引用而不是扩大堆内存来使改变小点,而服务器端,JRE通过扩大堆内存让性能更好。没有一种通用的方法。 + +### 回答2 +弱引用对象很快被收集。如果GC发现一个对象是弱引用(只能通过弱引用可达),它会立刻清除弱引用对象。同样的,对于在程序保持关联信息的对象保持一个引用是不错的,像关于类的缓存存储的反射信息或一个对象的包装器等等。没有意义地跟随相连对象的任何事物都会被清除掉。当弱引用清除掉时,它会进入到引用队列中,同时丢弃关联的对象。你保持关于对象额外的信息,但是一旦对象引用不要了,信息也就不需要了。总之,在某些情境下,你可以创建WeakReference的子类,保持在WeakReference的子类中对象的额外信息。WeakReference的其他典型应用是与Map连接,以保持规范化的例子。 + +在另一方面,软引用有利于外部缓存,再创造资源,因为GC会延迟清理他们。它能保证所有软引用会在内存溢出之前被清除,所以它们不会造成内存溢出。 + +典型的使用例子是保持从一个文件内容解析形式。在你载入文件,解析和与解析过代表的根对象保持一个软引用的地方扩展系统。在你下次需要文件时,你试图通过软引用恢复。如果可以恢复,你会在其他地方载入、解析你分享的文件,如果同时GC清理掉,你也可以重新载入。这样的话,你利用空内存可以做到性能最优化,但是不要内存溢出。 +光保持一个软引用不会造成溢出。如果在另一方面你误用软引用,且弱引用被使用了(也就是说,你保持与较强引用的对象相连的信息,然后当引用对象被清除,你也丢弃信息),你可能会内存溢出,因为在进入引用队列时,也许碰巧没有及时丢弃相连的对象。 + +所以,使用软引用还是弱引用是取决于用法的。如果你的信息构造起来较为复杂,但是尽管如此仍想从别的数据再构造信息,使用软引用。如果你对一些数据的规范化实例保持引用,或者你想对一个"不拥有的"对象保持引用(就是防止被垃圾回收),这样就使用弱引用。 + + +原文: +> http://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java \ No newline at end of file From dfc89235bb45818a5b4c5544bd847729441a8cb0 Mon Sep 17 00:00:00 2001 From: yu Date: Fri, 5 Aug 2016 14:27:19 +0800 Subject: [PATCH 038/108] what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java --- ...-reference-and-a-weak-reference-in-java.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md diff --git a/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md b/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md new file mode 100644 index 0000000..eb01281 --- /dev/null +++ b/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md @@ -0,0 +1,38 @@ +# Java中软引用和弱引用的区别 +## 问题 +题目就是问题 + +## 解答 +### 回答1 +从Ethan Nicholas的《Understanding Weak References》中 + +弱引用: +放置一个弱引用的作用,不是强有力强制一个对象保存在内存中。弱引用允许利用垃圾收集者的能力去决定可达性,所以你不需要自己做,你只需要创建一个软引用: + + WeakReference weakWidgt = new WeakReference(widgt); + +然后在代码别的地方你可以使用 `weakWidget.get()` 来获取真实的 `Widgt` 对象,当然弱引用足以强大能抵制垃圾收集器,所以你也许发现(如果没有强引用指向widget)`weakWidget.get()`突然开始返回null + +软引用 + +软引用就像弱引用一样,除了它不会着急将引用的对象扔出去。只有弱可达性的对象(这样的对象最强的引用只能是弱引用)将在下一次垃圾收集处理中被抛弃,但是软可达性的对象通常可以坚持一会。 + +软引用不要求与弱引用有什么不同,但是实际中,只要内存足够,软可达的对象通常会维持下去。对于缓存来说,这是个不错的基础,就像以上图像缓存描述,虽然可以让垃圾收集者担心对象是如何可达(一个强可达性的对象从不会从缓存中移除)和她们需要消耗多少内存 + +而且Peter Kessler备注到 + +Sun JRE 对待软引用和弱引用是不同的。如果内存是够用的。我们应坚持用软引用引用对象。一个细节是:对于客户端和服务器,JRE的政策是不同的:客户端,JRE试图保持通过清除软引用而不是扩大堆内存来使改变小点,而服务器端,JRE通过扩大堆内存让性能更好。没有一种通用的方法。 + +### 回答2 +弱引用对象很快被收集。如果GC发现一个对象是弱引用(只能通过弱引用可达),它会立刻清除弱引用对象。同样的,对于在程序保持关联信息的对象保持一个引用是不错的,像关于类的缓存存储的反射信息或一个对象的包装器等等。没有意义地跟随相连对象的任何事物都会被清除掉。当弱引用清除掉时,它会进入到引用队列中,同时丢弃关联的对象。你保持关于对象额外的信息,但是一旦对象引用不要了,信息也就不需要了。总之,在某些情境下,你可以创建WeakReference的子类,保持在WeakReference的子类中对象的额外信息。WeakReference的其他典型应用是与Map连接,以保持规范化的例子。 + +在另一方面,软引用有利于外部缓存,再创造资源,因为GC会延迟清理他们。它能保证所有软引用会在内存溢出之前被清除,所以它们不会造成内存溢出。 + +典型的使用例子是保持从一个文件内容解析形式。在你载入文件,解析和与解析过代表的根对象保持一个软引用的地方扩展系统。在你下次需要文件时,你试图通过软引用恢复。如果可以恢复,你会在其他地方载入、解析你分享的文件,如果同时GC清理掉,你也可以重新载入。这样的话,你利用空内存可以做到性能最优化,但是不要内存溢出。 +光保持一个软引用不会造成溢出。如果在另一方面你误用软引用,且弱引用被使用了(也就是说,你保持与较强引用的对象相连的信息,然后当引用对象被清除,你也丢弃信息),你可能会内存溢出,因为在进入引用队列时,也许碰巧没有及时丢弃相连的对象。 + +所以,使用软引用还是弱引用是取决于用法的。如果你的信息构造起来较为复杂,但是尽管如此仍想从别的数据再构造信息,使用软引用。如果你对一些数据的规范化实例保持引用,或者你想对一个"不拥有的"对象保持引用(就是防止被垃圾回收),这样就使用弱引用。 + + +原文: +> http://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java \ No newline at end of file From cbbb387fe8125c1890c9a7353418a93d9b0140cc Mon Sep 17 00:00:00 2001 From: "ziqiang.deng" Date: Tue, 9 Aug 2016 18:25:01 +0800 Subject: [PATCH 039/108] what-is-the-difference-between-jsf-servlet-and-jsp finished --- ...-difference-between-jsf-servlet-and-jsp.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 contents/what-is-the-difference-between-jsf-servlet-and-jsp.md diff --git a/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md b/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md new file mode 100644 index 0000000..93a31c7 --- /dev/null +++ b/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md @@ -0,0 +1,46 @@ +## JSF, Servlet 和 JSP (三种技术)有什么区别? + +###问题 +JSP 和 Servlet 有什么关系?JSP 是某种 Servlet 吗?JSP 和 JSF 又有什么关系?JSF 是某种基于JSP的,预构建好的 UI 吗,像 +ASP.NET-MVC 那样? + + +###回答1 + +#### JSP(Java Server Pages) +JSP 是一种运行在服务器上的Java 视图技术,它允许你写入模版化的文本(例如客户端代码 HTML, CSS, JavaScript等)。JSP 支持标签库(taglibs),标签库由Java 代码实现,让你可以动态地控制页面输出。JSTL 便是一种比较有名的标签库。JSP 同样支持表达式语言(expression language),表达式语言可以用来访问后台数据(页面上可用的属性,request/session 对象等等), 通常与标签库结合使用。 + +当一个 JSP 第一次被访问或者 webapp 启动时,servlet 容器会将 JSP 编译成一个继承了 HttpServlet 的类,然后在整个 webapp 生命周期内使用被编译后的类。可以在 servlet 容器的 work 目录下找到 JSP 对应的源代码。例如Tomcat 的 CATALINA.BASE/work 目录。 +当收到一个 JSP 请求时,servlet 容器会执行编译 JSP 生成的类,并将该类的输出(通常是 HTML/CSS/JS)发送到 客户端,客户端(WEB 浏览器) 会展示从服务端收到的内容。 + +#### Servlet +Servlet 是一种针对服务器端的 API,它用来响应客户端请求,并生成响应。比较有名的例子是 HttpServlet,它提供了响应 HTTP 请求(例如 GET POST)的方法。你可以从 web.xml 配置 HttpServlet 来监听某种 HTTP URL pattern 的请求,或者使用较新的 Java EE 6 @WebServlet 注解。 + +当 Servlet 第一次被请求,或者 webapp 启动时,servlet 容器会创建该 Servlet 的实例,并在整个 webapp 的生命周期维持该实例在内存中。同一个实例会被复用,来响应匹配到 URL pattern 的请求。可以通过 HttpServletRequest 访问请求里的数据,通过 HttpServletResponse 控制响应。上边两个对象会是 HttpServlet 的重载方法 doGet()和 doPost() 的参数。 + +#### JSF (JavaServer Faces) +JSF 是一个基于组件的MVC框架,建立在 Servlet API 基础上,JSF 通过标签库提供组件,标签库又可以用于 JSP 或者其它 Java 视图技术例如 Facelets. Facelets 更适合JSF。即它提供了很厉害的模版功能例如组合组件,而JSP 基本上只提供了 `` 来支持模版,所以 +当你想用一个组件替换一组重复出现的组件时,你不得不使用原生的 Java 代码来创建自定义组件(这在 JSF 里并不那么清晰明了,而且带来很多冗余工作)。为了推进 Facelets,自从 JSF 2.0 之后,JSP 这种视图技术已经被废弃了。 +作为一种 MVC(Model-View-Controller)框架,JSF 提供了唯一的 FacesServlet 请求/响应控制器。它负责所有的 HTTP 请求/响应工作, +例如 收集/校验/转换用户输入,将输入设置到 model 对象里,调用处理逻辑并输出响应。这样你基本上 只有一个 JSP或者 Facelets(XHTML) 页面用作视图,再加一个 Javabean 类当作 模型。 JSF 组件用来将模型和视图绑定起来(类似 ASP.NET web control 做的),然后 FacesServlet 使用 JSF 组件树来完成整个工作。 + +### 其它答案选编 + +参考以下链接 + +[http://www.oracle.com/technetwork/java/faq-137059.html](http://www.oracle.com/technetwork/java/faq-137059.html) + +[https://jcp.org/en/introduction/faq](https://jcp.org/en/introduction/faq) + +JSP 是一种特殊的Servlet。 + +JSF 是一个可以配合 JSP 使用的标签集。 + + +### stackoverflow原文链接: +[http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp](http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp) + + + + + From 984c94b04a0a095b8ab320abb59150786bc75348 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月17日 09:37:26 +0800 Subject: [PATCH 040/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../comparing-java-enum-members-or-equals.md | 165 +++++++++--------- contents/lookup-enum-by-string-value.md | 62 +------ 3 files changed, 89 insertions(+), 140 deletions(-) diff --git a/README.md b/README.md index e672a6b..b2e3b10 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ stackoverflow-Java-top-qa * [该什么时候使用 ThreadLocal变量,它是如何工作的](/contents/when-and-how-should-i-use-a-threadlocal-variable.md) * [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) * [如何计算MD5值](/contents/how-can-i-generate-an-md5-hash.md) +* [Java中软引用和弱引用的区别](/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md) > 编程技巧 @@ -140,7 +141,6 @@ stackoverflow-Java-top-qa - [How to create a generic array in Java?](http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) - [Why does Math.round(0.49999999999999994) return 1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) - [Eclipse: Set maximum line length for auto formatting?](http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting) -- [What is the difference between a soft reference and a weak reference in Java?](http://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java) - [What is the equivalent of the C++ Pair in Java?](http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java) - [What is the difference between JSF, Servlet and JSP?](http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp) - [How do I "decompile" Java class files?](http://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files) diff --git a/contents/comparing-java-enum-members-or-equals.md b/contents/comparing-java-enum-members-or-equals.md index 0bd407f..867246c 100644 --- a/contents/comparing-java-enum-members-or-equals.md +++ b/contents/comparing-java-enum-members-or-equals.md @@ -1,80 +1,85 @@ -# 比较java中枚举成员是用"=="还是equals() - -## 问题 -java枚举被编译成带有私有构造器和一堆public的静态成员的类。当比较枚举中的两个成员时,经常使用.equals()方法,例如 - public useEnums(SomeEnum a) - { - if(a.equals(SomeEnum.SOME_ENUM_VALUE)) - { - ... - } - ... - } -然而,偶然间使用"=="代替equals方法 - public useEnums2(SomeEnum a) - { - if(a == SomeEnum.SOME_ENUM_VALUE) - { - ... - } - ... - } -应该使用哪个呢? -## 解答 -### 回答1 -技术上来说,都是对的,如果你看了equals的源码,它简单地遵从"==" ,然而我一般使用"==" 因为它对于空指针,比较安全 -### 回答2 -#### 能在枚举时使用用"=="吗? - -可以,枚举值有小型实例控制,允许你用"=="去比较实例,在文档中有说明: - -JLS 8.9 枚举 -一个枚举类型除了定义的那些枚举常量外没有其他实例了。 -试图明确地说明一种枚举类型是会导致编译期异常。在枚举中final clone方法确保枚举常量从不会被克隆,而且序列化机制会确保从不会因为反序列化而创造复制的实例。枚举类型的反射实例化也是被禁止的。总之,以上内容确保了除了定义的枚举常量之外,没有枚举类型实例。 - -因为每个枚举常量只有一个实例,所以如果在比较两个参考值,至少有一个涉及到枚举常量时,允许使用"=="代替equals()。(equals()方法在枚举类中是一个final方法,在参数和返回结果时,很少调用父类的equals()方法,因此是一种恒等的比较。) - -这足够强力地支持Josh的建议,如果你坚持使用单例模式,最好的方法是用枚举类型强化单例属性(见Effective Java第二版中的第三条:用私有构造器或者枚举类型强化Singleton属性,或者单例模式的线程安全 ->http://stackoverflow.com/questions/2912281/thread-safety-in-singleton/ ) - -#### "=="和equals的区别 -通常情况下,==并不是可以替换equals,然而在枚举中是可以的。它们之间有两个重要的不同: - - "=="从不会抛出空指针异常 - - - enum Color { BLACK, WHITE }; - - Color nothing = null; - - if (nothing == Color.BLACK); // 正常运行 - - if (nothing.equals(Color.BLACK)); // 抛出空指 - 针异常 - -在编译期,"=="会检查其类型的兼容性 - - enum Color { BLACK, WHITE }; - enum Chiral { LEFT, RIGHT }; - - if (Color.BLACK.equals(Chiral.LEFT)); // 编译正常 - if (Color.BLACK == Chiral.LEFT); // 无法编译,类型不兼容 - -#### 在适用时,"=="可以被使用吗 - -Bloch(effective java的作者)明确指出不可变类可以控制它们实例保证客户端"=="是可用的。枚举就被明确地证明了 - -考虑静态工厂方法代替构造器 -它使得不可变的类可以确保不会存在两个相等的实例,即当且仅当a==b的时候才有a.equals(b)为true。如果类保证了这一点,它的客户端可以使用"=="操作符来代替equals(Object)方法,这样可以提升性能。枚举类型保证了这一点 - -总之,在枚举中使用"=="优势: - -- 能运行 -- 更快 -- 在运行期更安全 -- 在编译期更安全 - -备注:强有力的反击了那些认为foo.equals(bar)比foo==bar更有可读性的人们。 - -原文地址: -> http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals \ No newline at end of file +## 比较java枚举成员使用equal还是== + +### 问题 +我知道Java枚举会被编译成一个包含私有构造参数和一堆静态方法的类,当去比较两个枚举的时候,总是使用equals()方法,例如: +```java +public useEnums(SomeEnum a) +{ + if(a.equals(SomeEnum.SOME_ENUM_VALUE)) + { + ... + } + ... +} +``` +除此之外,我也可以使用 == 替代equals() 方法 +```java +public useEnums2(SomeEnum a) +{ + if(a == SomeEnum.SOME_ENUM_VALUE) + { + ... + } + ... +} +``` +我有5年以上的java编程经验,并且我想我也懂得 == 和 equals() 之间的区别,但是我仍然觉得很困惑,哪一个操作符才是我该使用的。 + +### 答案 + +二者皆对,如果你看过枚举的源码,你会发现在源码中,equals也仅仅非常简单的 == 。 +我使用 == ,因为无论如何,这个左值是可以为 null的 + + +译者补充 java.lang.Enum 中Equals 代码: +```java +public final boolean equals(Object other) { + return this==other; +} +``` + + +### 额外答案 +#### 能在枚举中使用 == 进行判断? +答案是肯定的,因为枚举有着严格的实例化控制,所以你可以用 == 去做比较符,这个用法,在官方文档中也有明确的说明。 + +>JLS 8.9 Enums +>An enum type has no instances other than those defined by its enum constants. +>It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum>ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures>that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types>is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by>the enum constants. +>Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the>equals method when comparing two object references if it is known that at least one of them refers to an enum ?>constant. (The equals method in Enum is a final method that merely invokes super.equals on its argument and ?>returns the result, thus performing an identity comparison.) + +#### 什么时候 == 和 equals 不一样? +As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals. When it is, however (such as with enum), there are two important differences to consider: +通常来说 == 不是一个 equals的一个备选方案,无论如何有2个重要的不同处需要考虑: + +##### == 不会抛出 NullPointerException +```java +enum Color { BLACK, WHITE }; + +Color nothing = null; +if (nothing == Color.BLACK); // runs fine +if (nothing.equals(Color.BLACK)); // throws NullPointerException +``` +##### == 在编译期检测类型兼容性 +```java +enum Color { BLACK, WHITE }; +enum Chiral { LEFT, RIGHT }; + +if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine +if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types! +``` + +#### 什么时候使用 == ? +Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that == is usable. enum is specifically mentioned to exemplify. +具体来说,那些提供恰当实例控制的不可变类能够保证 == 是可用的,枚举刚好符合这个条件。 + +> Item 1: Consider static factory methods instead of constructors +> [...] it allows an immutable class to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types provide this guarantee. + +总而言之,在枚举比较上使用 == , 因为: +1. 能正常工作 +2. 更快 +3. 运行时是安全的 +4. 编译期也是安全的 + +stackoverlfow链接:http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals diff --git a/contents/lookup-enum-by-string-value.md b/contents/lookup-enum-by-string-value.md index 05fd890..160aafa 100644 --- a/contents/lookup-enum-by-string-value.md +++ b/contents/lookup-enum-by-string-value.md @@ -1,63 +1,9 @@ -<<<<<<< HEAD -#通过String值查找enum中常量 -## 问题 -假设有一个枚举值 - public enum Blah - { - A,B,C,D - } -想通过一个String类型,找到所需要的枚举值。 -例如"A"->Blah.A -是使用Enum.valueOf()方法吗?该如何使用 -## 回答 -Blah.valueOf("A")会得到Blah.A -虽然api文档确实有静态方法valueOf()和values(),但是二者在编译期时才出现,而且在没出现在源程序中。 -例如可以采用Dialog.ModalityType显示了两种方法来处理这种情况。 -备注:Blah.valueOf("A")的方法是区分大小写,且不能含有空格。 - -如果String值与enum中不相同的查找方法: - - public enum Blah - { - A("text1"), - B("text2"), - C("text3"), - D("text4"); - private String text; - Blah(String text) - { - this.text = text; - } - public String getText() - { - return this.text; - } - - public static Blah fromString(String text) - { - if (text != null) - { - for (Blah b : Blah.values()) - { - if (text.equalsIgnoreCase(b.text)) - { - return b; - } - } - } - return null; - } - } - -备注:throw new IllegalArgumentException("No constant with text"+text+"found")会比直接抛出null更好 - -原文链接: -> http://stackoverflow.com/questions/604424/lookup-enum-by-string-value# +Java 中如何将 String 转换为 enum ======= -## Java 中如何将 String 转换为 enum ###问题 -我有一个 enum 类 + +###我有一个 enum 类 ``` java public enum Blah { @@ -159,5 +105,3 @@ _其他的答案都大同小异,感兴趣的可以看原帖_ stackoverflow链接 http://stackoverflow.com/questions/604424/lookup-enum-by-string-value _译者:[MagicWolf](https://github.com/DaiDongLiang)_ - ->>>>>>> upstream/master From 0edbc1809a580f004eeb5a79bfba442aba08080f Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月17日 09:42:40 +0800 Subject: [PATCH 041/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b2e3b10..1339808 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ stackoverflow-Java-top-qa * [该什么时候使用 ThreadLocal变量,它是如何工作的](/contents/when-and-how-should-i-use-a-threadlocal-variable.md) * [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) * [如何计算MD5值](/contents/how-can-i-generate-an-md5-hash.md) -* [Java中软引用和弱引用的区别](/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md) +* [Java中软引用和弱引用的区别](/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md) > 编程技巧 @@ -83,6 +83,7 @@ stackoverflow-Java-top-qa * [如何处理 java.lang.outOfMemoryError PermGen space error](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/dealing-with-java-lang-outofmemoryerror-permgen-space-error.md) * [如何在整数左填充0](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) * [在调用 instanceof 前需要进行null检查吗](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-null-check-needed-before-calling-instanceof.md) +* [如何从文件里读取字符串](/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md) > 网络 @@ -119,7 +120,6 @@ stackoverflow-Java-top-qa - [How to generate a random alpha-numeric string?](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) - [Comparing Java enum members: == or equals()?](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals) - [Failed to load the JNI shared Library (JDK)](http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk) -- [How to create a Java String from the contents of a file?](http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file) - [How do you assert that a certain exception is thrown in JUnit 4 tests?](http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests) - [What exactly is Apache Camel?](http://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel) - [How can I permanently have line numbers in IntelliJ?](http://stackoverflow.com/questions/13751/how-can-i-permanently-have-line-numbers-in-intellij) From 679cce1ed046af0585961f8d08d597d84f7bbd06 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月17日 09:47:16 +0800 Subject: [PATCH 042/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1339808..bfc5d1b 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ stackoverflow-Java-top-qa * [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) * [如何计算MD5值](/contents/how-can-i-generate-an-md5-hash.md) * [Java中软引用和弱引用的区别](/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md) +* [JSF, Servlet 和 JSP (三种技术)有什么区别](/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md) > 编程技巧 @@ -142,7 +143,6 @@ stackoverflow-Java-top-qa - [Why does Math.round(0.49999999999999994) return 1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) - [Eclipse: Set maximum line length for auto formatting?](http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting) - [What is the equivalent of the C++ Pair in Java?](http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java) -- [What is the difference between JSF, Servlet and JSP?](http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp) - [How do I "decompile" Java class files?](http://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files) - [Useful Eclipse Java Code Templates [closed]](http://stackoverflow.com/questions/1028858/useful-eclipse-java-code-templates) - [How to call SOAP web service in Android](http://stackoverflow.com/questions/297586/how-to-call-soap-web-service-in-android) From 1d7bcfa46010d7470957639bf0be72039b47160d Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月17日 10:06:34 +0800 Subject: [PATCH 043/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=90=90=E6=A7=BD?= =?UTF-8?q?=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bfc5d1b..93bb18c 100644 --- a/README.md +++ b/README.md @@ -10,20 +10,24 @@ stackoverflow-Java-top-qa ------------- ### 如何参与翻译(欢迎加入翻译组QQ群485011036) -如何参与: -- 请从下文"待翻译问题链接"中寻找你感兴趣的问答进行翻译。翻译好的问答,放到contents目录下,无需更新readme.md文档。之后提一个PR,我会对你的翻译做一个审校,并更新到readme中。 +####如何参与: +- 请从下文"待翻译问题链接"中寻找你感兴趣的问答进行翻译。翻译好的问答,放到contents目录下,无需更新readme.md文档。之后提一个PR,我负责合并PR并更新到readme中。 - 另外,为了避免多人重复新翻译一个问题,你可以提issue,说明你计划翻译的问题及时间点,我可以先更新到下面的"未翻译问题"中,说明已有人领了这个问题。当然,也不一定要提issue,一般情况下,只要及时提pr,我及时审核,出现"撞车"的概率并不高。 -一些基本的约定: +####一些基本的约定: - 文档的文件名,和stackoverflowhich-notnull-java-annotation-should-i-usew上的url保持一致。例如,http://stackoverflow.com/questions/8710619/java-operator 的文件名, 就是java-operator.md - 在每篇翻译文档内容的最后,要附上stackoverflow的原文链接 -每个人可以做(但不限于): +####每个人可以做(但不限于): - 找未翻译的问题进行翻译 - 优化已翻译的问题 - 输出问答精简汇总版(把所有的问答集中到一个md文件,然后尽量精简,让别人可以在一天内把这100个问题的精髓都看完) - 输出gitbook版本(现在直接在github上查看,体验不好) +####文档优化反馈: +请大家多多反馈,优化已翻译好的文章:可以到[吐槽区](https://github.com/giantray/stackoverflow-java-top-qa/issues/66)吐槽,也可以在已翻译文章基础上进行优化,提新的PR。文章质量的提升,需要大家一起努力! + + ### 目录 > 基础语法 From 8cc8fe4a14383c7de91ab7bde7897c5d9656b892 Mon Sep 17 00:00:00 2001 From: Troy Liu
Date: 2016年8月17日 10:48:00 +0800 Subject: [PATCH 044/108] ADD: java-inner-class-and-static-nested-class.md --- ...ava-inner-class-and-static-nested-class.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 contents/java-inner-class-and-static-nested-class.md diff --git a/contents/java-inner-class-and-static-nested-class.md b/contents/java-inner-class-and-static-nested-class.md new file mode 100644 index 0000000..e6d08c2 --- /dev/null +++ b/contents/java-inner-class-and-static-nested-class.md @@ -0,0 +1,44 @@ +## Java内部类和嵌套静态类 + +### 问题 +Java 当中的内部类和静态嵌套类有什么主要区别? 在这两者中有什么设计或者实现么? + +### 回答 +嵌套类分为两类: 静态和非静态. 用`static`装饰的嵌套类叫做静态类, 非静态的嵌套类叫做内部类. + +静态嵌套类使用外围类名来访问: +```java +OuterClass.StaticNestedClass +``` +例如, 实例化一个静态嵌套类的对象就要使用这种语法: +```java +OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); +``` + +内部类对象的存在需要依靠一个外部类的对象. 看看下面的类: +```java +class OuterClass { + ... + class InnerClass { + ... + } +} +``` +内部类对象只有当外部类对象存在时才有效, 并且可以直接访问他的包裹对象(外部类对象)的方法以及成员. + +因此, 要实例化一个内部类对象, 必须先实例化外部类对象. 然后用这种语法来创建内部类对象: +```java +OuterClass.InnerClass innerObject = outerObject.new InnerClass(); +``` +参考: [Java Tutorial - Nested Classes](http://download.oracle.com/javase/tutorial/java/javaOO/nested.html) + +提醒一下, 还有一种不用外部类对象来创建内部类对象的方法: [inner class without an enclosing ](http://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance) +```java +class A { + int t() { return 1; } + static A a = new A() { int t() { return 2; } }; +} +``` +在这里, `new A() { ... }`是一个定义在静态上下文的内部类对象, 并没有一个外围对象. + +stackoverflow链接: [Java inner class and static nested class](http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class) From 63083bfc942599b665479d5260bf93bbe68d1eee Mon Sep 17 00:00:00 2001 From: yu Date: 2016年8月17日 15:21:06 +0800 Subject: [PATCH 045/108] owen1190 --- contents/comparing-java-enum-members-or-equals.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contents/comparing-java-enum-members-or-equals.md b/contents/comparing-java-enum-members-or-equals.md index 867246c..a83be17 100644 --- a/contents/comparing-java-enum-members-or-equals.md +++ b/contents/comparing-java-enum-members-or-equals.md @@ -44,10 +44,10 @@ public final boolean equals(Object other) { 答案是肯定的,因为枚举有着严格的实例化控制,所以你可以用 == 去做比较符,这个用法,在官方文档中也有明确的说明。 >JLS 8.9 Enums ->An enum type has no instances other than those defined by its enum constants. ->It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum>ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures>that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types>is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by>the enum constants. ->Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the>equals method when comparing two object references if it is known that at least one of them refers to an enum ?>constant. (The equals method in Enum is a final method that merely invokes super.equals on its argument and ?>returns the result, thus performing an identity comparison.) +一个枚举类型除了定义的那些枚举常量外没有其他实例了。 +试图明确地说明一种枚举类型是会导致编译期异常。在枚举中final clone方法确保枚举常量从不会被克隆,而且序列化机制会确保从不会因为反序列化而创造复制的实例。枚举类型的反射实例化也是被禁止的。总之,以上内容确保了除了定义的枚举常量之外,没有枚举类型实例。 +因为每个枚举常量只有一个实例,所以如果在比较两个参考值,至少有一个涉及到枚举常量时,允许使用"=="代替equals()。(equals()方法在枚举类中是一个final方法,在参数和返回结果时,很少调用父类的equals()方法,因此是一种恒等的比较。) #### 什么时候 == 和 equals 不一样? As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals. When it is, however (such as with enum), there are two important differences to consider: 通常来说 == 不是一个 equals的一个备选方案,无论如何有2个重要的不同处需要考虑: @@ -73,8 +73,8 @@ if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types! Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that == is usable. enum is specifically mentioned to exemplify. 具体来说,那些提供恰当实例控制的不可变类能够保证 == 是可用的,枚举刚好符合这个条件。 -> Item 1: Consider static factory methods instead of constructors -> [...] it allows an immutable class to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types provide this guarantee. +考虑静态工厂方法代替构造器 +它使得不可变的类可以确保不会存在两个相等的实例,即当且仅当a==b的时候才有a.equals(b)为true。如果类保证了这一点,它的客户端可以使用"=="操作符来代替equals(Object)方法,这样可以提升性能。枚举类型保证了这一点 总而言之,在枚举比较上使用 == , 因为: 1. 能正常工作 From 9e9aa6e687a75cc19b1505f3bc02f571229422dd Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月17日 17:34:41 +0800 Subject: [PATCH 046/108] add->whats-the-difference-between-component-repository-service-annotations-in.md --- ...onent-repository-service-annotations-in.md | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 contents/whats-the-difference-between-component-repository-service-annotations-in.md diff --git a/contents/whats-the-difference-between-component-repository-service-annotations-in.md b/contents/whats-the-difference-between-component-repository-service-annotations-in.md new file mode 100644 index 0000000..be6945a --- /dev/null +++ b/contents/whats-the-difference-between-component-repository-service-annotations-in.md @@ -0,0 +1,77 @@ +## @Component, @Repository, @Service的区别 + +#### 问题 + +在spring集成的框架中,注解在类上的`@Component`,`@Repository`,`@Service`等注解能否被互换?即这些注解的区别是什么? + +#### 回答1 + +引用spring的官方文档中的一段描述: + +在Spring2.0之前的版本中,`@Repository`注解可以标记在任何的类上,用来表明该类是用来执行与数据库相关的操作(即dao对象) + +在Spring2.5版本中,引入了更多的Spring类注解:`@Component`,`@Service`,`@Controller`。`Component`是一个通用的Spring容器管理的单例bean组件。而`@Repository`, `@Service`, `@Controller`就是针对不同的使用场景所采取的特定功能化的注解组件。 + +因此,当你的一个类被`@Component`所注解,那么就意味着同样可以用`@Repository`, `@Service`, `@Controller`来替代它,同时这些注解会具备有更多的功能,而且功能各异。 + +最后,如果你不知道要在项目的业务层采用`@Service`还是`@Component`注解。那么,`@Service`是一个更好的选择。 + +就如上文所说的,`@Repository`早已被支持了在你的持久层作为一个标记可以去自动处理数据库操作产生的异常(译者注:因为原生的java操作数据库所产生的异常只用了几种,但是产生的原因却有很多种,这样对于数据库操作的报错排查造成了一定的影响;而Spring拓展了原生的持久层异常,针对不同的产生原因有了更多的异常进行描述。所以,在注解了`@Repository`的类上如果数据库操作中抛出了异常,就能对其进行处理,转而抛出的是翻译后的spring专属数据库异常)。 + +| 注解 | 含义 | +| ------------- |:-------------:| +| @Component | 最普通的组件,可以被注入到spring容器进行管理 | +| @Repository | 作用于持久层 | +| @Service | 作用于业务逻辑层 | +| @Controller | 作用于表现层(spring-mvc的注解) | + +#### 回答2 + +这几个注解几乎可以说是一样的:因为被这些注解修饰的类就会被Spring扫描到并注入到Spring的bean容器中。 + +这里,有两个注解是不能被其他注解所互换的: + +* `@Controller` 注解的bean会被spring-mvc框架所使用。 +* `@Repository` 会被作为持久层操作(数据库)的bean来使用 + +如果想使用自定义的组件注解,那么只要在你定义的新注解中加上`@Component`即可: + +```java +@Component +@Scope("prototype") +public @interface ScheduleJob {...} +``` + +这样,所有被`@ScheduleJob`注解的类就都可以注入到spring容器来进行管理。我们所需要做的,就是写一些新的代码来处理这个自定义注解(译者注:可以用反射的方法),进而执行我们想要执行的工作。 + +#### 回答3 + +`@Component`就是跟``一样,可以托管到Spring容器进行管理。 + +@Service, @Controller , @Repository = {@Component + 一些特定的功能}。这个就意味着这些注解在部分功能上是一样的。 + +当然,下面三个注解被用于为我们的应用进行分层: + +* `@Controller`注解类进行前端请求的处理,转发,重定向。包括调用Service层的方法 +* `@Service`注解类处理业务逻辑 +* `@Repository`注解类作为DAO对象(数据访问对象,Data Access Objects),这些类可以直接对数据库进行操作 + +有这些分层操作的话,代码之间就实现了松耦合,代码之间的调用也清晰明朗,便于项目的管理;假想一下,如果只用`@Controller`注解,那么所有的请求转发,业务处理,数据库操作代码都糅合在一个地方,那这样的代码该有多难拓展和维护。 + +#### 总结 + +* `@Component`, `@Service`, `@Controller`, `@Repository`是spring注解,注解后可以被spring框架所扫描并注入到spring容器来进行管理 +* `@Component`是通用注解,其他三个注解是这个注解的拓展,并且具有了特定的功能 +* `@Repository`注解在持久层中,具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能。 +* `@Controller`层是spring-mvc的注解,具有将请求进行转发,重定向的功能。 +* `@Service`层是业务逻辑层注解,这个注解只是标注该类处于业务逻辑层。 +* 用这些注解对应用进行分层之后,就能将请求处理,义务逻辑处理,数据库操作处理分离出来,为代码解耦,也方便了以后项目的维护和开发。 + +#### Stackoverflow链接: + +[http://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in](http://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in) + +#### 拓展 + +1. [Spring注解@Component、@Repository、@Service、@Controller区别](http://www.cnblogs.com/JAYIT/p/5593169.html) +2. [Spring注解@Autowired、@Resource区别](http://www.cnblogs.com/leiOOlei/p/3713779.html) \ No newline at end of file From 13fd9c69a9c9e5d71716c77d545265f470618014 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月17日 22:22:01 +0800 Subject: [PATCH 047/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 93bb18c..6688723 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ stackoverflow-Java-top-qa * [如何计算MD5值](/contents/how-can-i-generate-an-md5-hash.md) * [Java中软引用和弱引用的区别](/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md) * [JSF, Servlet 和 JSP (三种技术)有什么区别](/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md) +* [Java内部类和嵌套静态类](/contents/java-inner-class-and-static-nested-class.md) > 编程技巧 @@ -118,7 +119,6 @@ stackoverflow-Java-top-qa - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) - [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) - [Android SDK installation doesn't find JDK](http://stackoverflow.com/questions/4382178/android-sdk-installation-doesnt-find-jdk) -- [Java inner class and static nested class](http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class) - ['Must Override a Superclass Method' Errors after importing a project into Eclipse](http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) From 8fffae44b2b507d42c67510980c4e8c7be3cc980 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月17日 22:28:29 +0800 Subject: [PATCH 048/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6688723..defedb3 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ stackoverflow-Java-top-qa * [Java中软引用和弱引用的区别](/contents/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java.md) * [JSF, Servlet 和 JSP (三种技术)有什么区别](/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md) * [Java内部类和嵌套静态类](/contents/java-inner-class-and-static-nested-class.md) +* [@Component, @Repository, @Service的区别](/contents/whats-the-difference-between-component-repository-service-annotations-in.md) > 编程技巧 @@ -139,7 +140,6 @@ stackoverflow-Java-top-qa - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) - [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) - [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) -- [What's the difference between @Component, @Repository & @Service annotations in Spring?](http://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in) - [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) - [Why does this go into an infinite loop?](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) - [decompiling DEX into Java sourcecode](http://stackoverflow.com/questions/1249973/decompiling-dex-into-java-sourcecode) From 85619235f92d2b2d14012c92c2e0ba01bb972d8d Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月17日 23:24:57 +0800 Subject: [PATCH 049/108] add->iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md --- ...concurrentmodificationexception-when-re.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md diff --git a/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md b/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md new file mode 100644 index 0000000..47195c4 --- /dev/null +++ b/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md @@ -0,0 +1,69 @@ +## 遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出 + +#### 问题: + +在遍历集合的过程中,不会总出现`ConcurrentModificationException`异常的抛出,但是在下面的代码块中: + +```java +public static void main(String[] args) { + Collection l = new ArrayList(); + + for (int i=0; i < 10; ++i) { + l.add(new Integer(4)); + l.add(new Integer(5)); + l.add(new Integer(6)); + } + + //遍历的过程中移除部分集合元素 + for (Integer i : l) { + if (i.intValue() == 5) { + l.remove(i); + } + } + + System.out.println(l); +} +``` + +运行之后,结果显而易见,总是会抛出异常: + +```java +Exception in thread "main" java.util.ConcurrentModificationException +``` + +所以,遍历集合时移除元素,怎样避免ConcurrentModificationException异常的产生?有什么好的解决办法? + +#### 回答: + +`Iterator.remove()`是线程安全的,所以你的代码可以这样写: + +```java +List list = new ArrayList(); + +for (Iterator iterator = list.iterator(); iterator.hasNext();) { + String string = iterator.next(); + if (string.isEmpty()) { + + // 从迭代器中移除集合元素,集合中相应的集合元素也会安全地被移除 + // 在这里,如果继续调用的是list.remove(string),那么仍会抛出异常 + iterator.remove(); + } +} +``` + +在遍历集合时修改集合的结构或内容的情况中,`Iterator.remove()`是唯一线程安全的方法。 + +#### 问题原因: + +fail-fast, 快速失败机制,是java集合类的一种错误检查机制。当有多个线程同时对集合进行遍历以及内容或者结构的修改时,就有可能产生fail-fast机制。这意味着,当它们发现容器在迭代的过程中被修改时,就会抛出一个ConcurrentModificationException异常。 + +迭代器的快速失败行为无法得到保证,它不能保证一定会出现该错误,但是快速失败操作会尽最大努力抛出ConcurrentModificationException异常,这个异常仅用于检测bug。这种迭代器并不是完备的处理机制,而只是作为并发问题的一个预警指示器。 + + +#### 拓展阅读: + +[fail-fast机制的原理解析](https://github.com/AcceptedBoy/backstage-vacation-plan/blob/master/chapter1/concurrency/fail-fast.md) + +#### StackOverFlow地址: + +[http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) \ No newline at end of file From 5ebf82154ce017de5d4cfd114acb97a1ecc9d930 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月18日 08:57:56 +0800 Subject: [PATCH 050/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index defedb3..807429a 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ stackoverflow-Java-top-qa * [如何在整数左填充0](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) * [在调用 instanceof 前需要进行null检查吗](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-null-check-needed-before-calling-instanceof.md) * [如何从文件里读取字符串](/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md) +* [遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出](/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-reiterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md) > 网络 @@ -135,7 +136,6 @@ stackoverflow-Java-top-qa - [Can I add jars to maven 2 build classpath without installing them?](http://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them) - [Update Eclipse with Android development tools v. 23](http://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-v-23) - [Setting multiple jars in java classpath](http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath) -- [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) - [What is the Java equivalent for LINQ?](http://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) - [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) From 62805417211533ebb9a27b306853264151f84800 Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月18日 10:57:34 +0800 Subject: [PATCH 051/108] add->how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md --- ...in-exception-is-thrown-in-junit-4-tests.md | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md diff --git a/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md b/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md new file mode 100644 index 0000000..84ca09e --- /dev/null +++ b/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md @@ -0,0 +1,63 @@ +## JUnit如何断言一个确定的异常抛出 + +#### 问题 + +在JUnit4单元测试中,我要怎样做才能测试出有特定的异常抛出?我能想到的就只有下面的方法: + +```java +@Test +public void testFooThrowsIndexOutOfBoundsException() { + boolean thrown = false; + + try { + foo.doStuff(); + } catch (IndexOutOfBoundsException e) { + thrown = true; + } + + assertTrue(thrown); +} +``` + +#### 回答1 + +在JUnit4后支持下面的写法: +```java +@Test(expected=IndexOutOfBoundsException.class) +public void testIndexOutOfBoundsException() { + ArrayList emptyList = new ArrayList(); + Object o = emptyList.get(0); +} +``` +(译者:在`@Test`注解内提供了`expected`属性,你可以用它来指定一个`Throwble`类型,如果方法调用中抛出了这个异常,那么这条测试用例就相当于通过了) + +#### 回答2 + +如果你使用的是JUnit4.7,你可以使用如下的期望异常规则来验证异常信息: + +```java +public class FooTest { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void doStuffThrowsIndexOutOfBoundsException() { + Foo foo = new Foo(); + + exception.expect(IndexOutOfBoundsException.class); + foo.doStuff(); + } +} +``` + +这种方式比`@Test(expected=IndexOutOfBoundsException.class)`要更好,如果是在调用`foo.doStuff()`方法之前就已经抛出异常的话,测试结果就不是我们想要的了。 +(译者:同时,`ExpectedException`还能够验证异常信息,如`exception.expectMessage("there is an exception!");` + +#### 拓展阅读 + +1. [JUnit:使用ExpectedException进行异常测试](http://www.tuicool.com/articles/ANviIz) +2. [JUnit4 用法详解](http://www.blogjava.net/jnbzwm/archive/2010/12/15/340801.html) + +#### StackOverflow地址: + +[http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests](http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests) \ No newline at end of file From 01ca9246a07be21901ba15ab4ceb7f2bbedb5102 Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月18日 11:39:57 +0800 Subject: [PATCH 052/108] update->junit4 && add->create_generic_array --- ...in-exception-is-thrown-in-junit-4-tests.md | 2 +- .../how-to-create-a-generic-array-in-java.md | 76 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 contents/how-to-create-a-generic-array-in-java.md diff --git a/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md b/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md index 84ca09e..6c5cbdf 100644 --- a/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md +++ b/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md @@ -1,4 +1,4 @@ -## JUnit如何断言一个确定的异常抛出 +## JUnit4如何断言确定异常的抛出 #### 问题 diff --git a/contents/how-to-create-a-generic-array-in-java.md b/contents/how-to-create-a-generic-array-in-java.md new file mode 100644 index 0000000..d1d7041 --- /dev/null +++ b/contents/how-to-create-a-generic-array-in-java.md @@ -0,0 +1,76 @@ +## 如何创建泛型java数组 + +#### 问题 + +数组是不能通过泛型创建的,因为我们不能创建不可具体化的类型的数组。如下面的代码: + +```java +public class GenSet { + private E a[]; + + public GenSet() { + a = new E[INITIAL_ARRAY_LENGTH]; //编译期就会报错:不能创建泛型数组 + } +} +``` + +#### 采纳答案 + +* 检查:强类型。`GenSet`明确知道数组中包含的类型是什么(例如通过构造器传入`Class`,当方法中传入类型不是`E`将抛出异常) + +```java +public class GenSet { + + private E[] a; + + public GenSet(Class c, int s) { + // 使用原生的反射方法,在运行时知道其数组对象类型 + @SuppressWarnings("unchecked") + final E[] a = (E[]) Array.newInstance(c, s); + this.a = a; + } + + E get(int i) { + return a[i]; + } + + //...如果传入参数不为E类型,那么强制添加进数组将会抛出异常 + void add(E e) {...} +} +``` + +* 未检查:弱类型。数组内对象不会有任何类型检查,而是作为Object类型传入。 + +在这种情况下,你可以采取如下写法: + +```java +public class GenSet { + + private Object[] a; + + public GenSet(int s) { + a = new Object[s]; + } + + E get(int i) { + @SuppressWarnings("unchecked") + final E e = (E) a[i]; + return e; + } +} +``` + +上述代码在编译期能够通过,但因为泛型擦除的缘故,在程序执行过程中,数组的类型有且仅有`Object`类型存在,这个时候如果我们强制转化为`E`类型的话,在运行时会有`ClassCastException`抛出。所以,要确定好泛型的上界,将上边的代码重写一下: + +```java +public class GenSet { // E has an upper bound of Foo + + private Foo[] a; // E 泛型在运行期会被擦除为Foo类型,所以这里使用Foo[] + + public GenSet(int s) { + a = new Foo[s]; + } + + //... +} +``` \ No newline at end of file From 6aaae682e3f0a46cbbf04ea8f7af2edef0b333b1 Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月18日 11:42:02 +0800 Subject: [PATCH 053/108] add_stackoverflow_address->create_generic_array --- contents/how-to-create-a-generic-array-in-java.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/contents/how-to-create-a-generic-array-in-java.md b/contents/how-to-create-a-generic-array-in-java.md index d1d7041..086f0d2 100644 --- a/contents/how-to-create-a-generic-array-in-java.md +++ b/contents/how-to-create-a-generic-array-in-java.md @@ -73,4 +73,8 @@ public class GenSet { // E has an upper bound of Foo //... } -``` \ No newline at end of file +``` + +#### StackOverflow地址: + +[http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java](http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) \ No newline at end of file From 86bf2258cbff6c89ac2f05c904e885fb3e2d8d86 Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月18日 18:57:37 +0800 Subject: [PATCH 054/108] add->how-can-i-create-an-executable-jar-with-dependencies-using-maven.md --- ...table-jar-with-dependencies-using-maven.md | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md diff --git a/contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md b/contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md new file mode 100644 index 0000000..dab0dcf --- /dev/null +++ b/contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md @@ -0,0 +1,99 @@ +## 如何使用maven把项目及其依赖打包为可运行jar包 + +#### 问题 + +我想把java项目打包为可运行的分布式jar包。我该怎样做,才能把项目中maven所依赖的jar包导入到我的项目jar包中? + +#### 回答 + +在`pom.xml`文件中,加入如下的插件: + +```xml + + + + maven-assembly-plugin + + + + + fully.qualified.MainClass + + + + jar-with-dependencies + + + + + +``` + +之后,运行maven命令: + +> mvn clean compile assembly:single + +`clean`,`compile`,`assembly:single`任务将会依次被执行;`compile`任务必须写在`assembly:single`之前,否则打包后的jar包内将不会有你的编译代码。 + +(译注:执行完后,会在你的maven项目的target目录下,生成想要的jar包,而不再需要使用`mvn package`命令进行打包) + +通常情况下,上述maven命令执行后会自动绑定到项目的构建阶段,从而保证了以后在执行`mvn install`命令时的jar包也会被构建。 +(译注:下面是实际上完整的默认的`pom.xml`配置,只不过``可以被省略,若省略则按照下述默认的配置执行) + +```xml + + maven-assembly-plugin + + + + fully.qualified.MainClass + + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + +``` + +#### 拓展 + +怎样去运行打包后的可运行jar包? + +* 对上述配置中已经指定了`main`函数所在类的jar包,打开命令行窗口,输入命令: + +```java +java -jar jar包的路径/jar包的名字.jar +``` + +例如: + +```Auto +java -jar D:\my_java_project\maven_test.jar +``` + +* 若在pom.xml并没有指定`main`方法所在类,那么该jar的运行应采取如下命令: + +```java +java -cp jar包的路径/jar包的名字.jar main方法所在类的全限定名 +``` + +例如: + +```java +java -cp D:\my_java_project\maven_test.jar com.my.path.MainClass +``` + + +#### StackOverflow地址 + +[http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven](http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven) \ No newline at end of file From 46310586da02ee4ce8e924b70db6d0d23bb22caa Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月18日 19:23:17 +0800 Subject: [PATCH 055/108] add->intellij && update->difference of spring annotation --- ...rmanently-have-line-numbers-in-intellij.md | 29 +++++++++++++++++++ ...onent-repository-service-annotations-in.md | 6 ++-- 2 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 contents/how-can-i-permanently-have-line-numbers-in-intellij.md diff --git a/contents/how-can-i-permanently-have-line-numbers-in-intellij.md b/contents/how-can-i-permanently-have-line-numbers-in-intellij.md new file mode 100644 index 0000000..8f7e071 --- /dev/null +++ b/contents/how-can-i-permanently-have-line-numbers-in-intellij.md @@ -0,0 +1,29 @@ +## 如何让IntelliJ编辑器永久性显示代码行数 + +#### 问题 + +如何让IntelliJ编辑器永久性显示代码行数 + +#### 回答 + +##### IntelliJ 14.0之后的版本 + +打开软件的菜单`File`->`Settings`->`Editor`->`General`->`Appearance`,在右侧的配置`Show line numbers`打勾: +![image1][1] + +##### IntelliJ 8.1.2 - 13.X的版本 + +打开软件的菜单`File`->`Settings`->`Editor`->`Appearance`,在右侧的配置`Show line numbers`打勾: +![images2][2] + +#### 拓展 + +[IntelliJ IDEA 使用教程](http://www.phperz.com/article/15/0923/159068.html) + +#### StackOverflow地址 + +http://stackoverflow.com/questions/13751/how-can-i-permanently-have-line-numbers-in-intellij + + + [1]: http://i.stack.imgur.com/9DL9q.png + [2]: http://i.stack.imgur.com/JVZlJ.jpg \ No newline at end of file diff --git a/contents/whats-the-difference-between-component-repository-service-annotations-in.md b/contents/whats-the-difference-between-component-repository-service-annotations-in.md index be6945a..0dd4196 100644 --- a/contents/whats-the-difference-between-component-repository-service-annotations-in.md +++ b/contents/whats-the-difference-between-component-repository-service-annotations-in.md @@ -2,13 +2,13 @@ #### 问题 -在spring集成的框架中,注解在类上的`@Component`,`@Repository`,`@Service`等注解能否被互换?即这些注解的区别是什么? +在spring集成的框架中,注解在类上的`@Component`,`@Repository`,`@Service`等注解能否被互换?或者说这些注解有什么区别? #### 回答1 引用spring的官方文档中的一段描述: -在Spring2.0之前的版本中,`@Repository`注解可以标记在任何的类上,用来表明该类是用来执行与数据库相关的操作(即dao对象) +在Spring2.0之前的版本中,`@Repository`注解可以标记在任何的类上,用来表明该类是用来执行与数据库相关的操作(即dao对象),并支持自动处理数据库操作产生的异常 在Spring2.5版本中,引入了更多的Spring类注解:`@Component`,`@Service`,`@Controller`。`Component`是一个通用的Spring容器管理的单例bean组件。而`@Repository`, `@Service`, `@Controller`就是针对不同的使用场景所采取的特定功能化的注解组件。 @@ -16,7 +16,7 @@ 最后,如果你不知道要在项目的业务层采用`@Service`还是`@Component`注解。那么,`@Service`是一个更好的选择。 -就如上文所说的,`@Repository`早已被支持了在你的持久层作为一个标记可以去自动处理数据库操作产生的异常(译者注:因为原生的java操作数据库所产生的异常只用了几种,但是产生的原因却有很多种,这样对于数据库操作的报错排查造成了一定的影响;而Spring拓展了原生的持久层异常,针对不同的产生原因有了更多的异常进行描述。所以,在注解了`@Repository`的类上如果数据库操作中抛出了异常,就能对其进行处理,转而抛出的是翻译后的spring专属数据库异常)。 +就如上文所说的,`@Repository`早已被支持了在你的持久层作为一个标记可以去自动处理数据库操作产生的异常(译者注:因为原生的java操作数据库所产生的异常只定义了几种,但是产生数据库异常的原因却有很多种,这样对于数据库操作的报错排查造成了一定的影响;而Spring拓展了原生的持久层异常,针对不同的产生原因有了更多的异常进行描述。所以,在注解了`@Repository`的类上如果数据库操作中抛出了异常,就能对其进行处理,转而抛出的是翻译后的spring专属数据库异常,方便我们对异常进行排查处理)。 | 注解 | 含义 | | ------------- |:-------------:| From 1bac5e9d3b32b0ddecffbc2d958f26099f32bd39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BF=8E=E9=87=91=E5=A5=BD?= Date: 2016年8月22日 18:23:37 +0800 Subject: [PATCH 056/108] android-sdk-installation-doesnt-find-jdk --- ...ndroid-sdk-installation-doesnt-find-jdk.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 contents/android-sdk-installation-doesnt-find-jdk.md diff --git a/contents/android-sdk-installation-doesnt-find-jdk.md b/contents/android-sdk-installation-doesnt-find-jdk.md new file mode 100644 index 0000000..7b70797 --- /dev/null +++ b/contents/android-sdk-installation-doesnt-find-jdk.md @@ -0,0 +1,30 @@ +##安装Android SDK的时候找不到JDK + +###问题 +我在我的win7 64位的系统上安装Android SDK时,jdk-6u23-windows-x64.exe已经安装上了,但是Android SDK的安装程序却因为找不到已安装的JDK无法继续下去。 +这个问题出现过吗?有没有办法解决呢? + +![](http://ww2.sinaimg.cn/large/0060lm7Tgw1f72ny3m6oaj30ds0a0gmi.jpg) + +###回答1: +当你看到这个提示(找不到jdk)的时候按Back(返回),然后再点Next(下一步)。这个时候,它将会去寻找JDK + +###回答2: +实际安装: + + - 系统:windows 8.1 + - JDK文件: jdk-8u11-windows-x64.exe + - ADT文件:installer_r23.0.2-windows.exe +安装64位JDK,然后尝试第一个回答中的back-next的方法。然后尝试设置JAVA_HOME 根据错误信息的提示,但是,仍旧对我没有用处,然后,尝试如下解决办法: + +按照它说的做,设置JAVA_HOME在你的系统环境变量中,这个路径要使用正斜杠(/)而非反斜杠(\) + +**注意:** +当我把JAVA_HOME设置为C:\Program Files\Java\jdk1.6.0_31的时候还是不行,但是当我设置成C:/Program Files/Java/jdk1.6.0_31的时候就ok了。快把我逼疯了。 + +如果还不行,就把 %JAVA_HOME%加在环境变量Path的头部。 + +下面是我的环境变量的配置: + - JAVA_HOME=C:/Program Files/Java/jdk1.8.0_11 + - JRE_HOME=C:/Program Files/Java/jre8 + - Path=%JAVA_HOME%;C:... From bca7ea7d4d6d405a15a83cdfb4cd2d21051020fd Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月22日 23:33:56 +0800 Subject: [PATCH 057/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 807429a..443a313 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ stackoverflow-Java-top-qa * [JSF, Servlet 和 JSP (三种技术)有什么区别](/contents/what-is-the-difference-between-jsf-servlet-and-jsp.md) * [Java内部类和嵌套静态类](/contents/java-inner-class-and-static-nested-class.md) * [@Component, @Repository, @Service的区别](/contents/whats-the-difference-between-component-repository-service-annotations-in.md) +* [如何创建泛型java数组](/contents/how-to-create-a-generic-array-in-java.md) > 编程技巧 @@ -92,7 +93,8 @@ stackoverflow-Java-top-qa * [在调用 instanceof 前需要进行null检查吗](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-null-check-needed-before-calling-instanceof.md) * [如何从文件里读取字符串](/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md) * [遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出](/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-reiterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md) - +* [如何让IntelliJ编辑器永久性显示代码行数](/contents/how-can-i-permanently-have-line-numbers-in-intellij.md) +* [如何使用maven把项目及其依赖打包为可运行jar包](/contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md) > 网络 @@ -109,6 +111,7 @@ stackoverflow-Java-top-qa > 测试 * [如何测试 private 方法,变量或者内部类](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes.md) +* [JUnit4如何断言确定异常的抛出](/contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md) > Android @@ -117,7 +120,6 @@ stackoverflow-Java-top-qa ### 待翻译问题链接(还剩x问题) - [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) -- [How can I create an executable jar with dependencies using Maven?](http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) - [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) - [Android SDK installation doesn't find JDK](http://stackoverflow.com/questions/4382178/android-sdk-installation-doesnt-find-jdk) @@ -127,9 +129,7 @@ stackoverflow-Java-top-qa - [How to generate a random alpha-numeric string?](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) - [Comparing Java enum members: == or equals()?](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals) - [Failed to load the JNI shared Library (JDK)](http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk) -- [How do you assert that a certain exception is thrown in JUnit 4 tests?](http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests) - [What exactly is Apache Camel?](http://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel) -- [How can I permanently have line numbers in IntelliJ?](http://stackoverflow.com/questions/13751/how-can-i-permanently-have-line-numbers-in-intellij) - [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) - [How do I discover memory usage of my application in Android?](http://stackoverflow.com/questions/2298208/how-do-i-discover-memory-usage-of-my-application-in-android) - [Uncatchable ChuckNorrisException](http://stackoverflow.com/questions/13883166/uncatchable-chucknorrisexception) @@ -143,7 +143,6 @@ stackoverflow-Java-top-qa - [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) - [Why does this go into an infinite loop?](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) - [decompiling DEX into Java sourcecode](http://stackoverflow.com/questions/1249973/decompiling-dex-into-java-sourcecode) -- [How to create a generic array in Java?](http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) - [Why does Math.round(0.49999999999999994) return 1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) - [Eclipse: Set maximum line length for auto formatting?](http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting) - [What is the equivalent of the C++ Pair in Java?](http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java) From f54a51d12bc98629f1f2469f1910608657cd38c9 Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月22日 23:46:12 +0800 Subject: [PATCH 058/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- contents/android-sdk-installation-doesnt-find-jdk.md | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 443a313..e57f95e 100644 --- a/README.md +++ b/README.md @@ -117,12 +117,12 @@ stackoverflow-Java-top-qa * [在Android里面下载文件,并在ProgressDialog显示进度](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog.md) * [如何获取Android设备唯一ID](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-there-a-unique-android-device-id.md) +* [安装Android SDK的时候找不到JDK](contents/android-sdk-installation-doesnt-find-jdk.md) ### 待翻译问题链接(还剩x问题) - [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) - [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) -- [Android SDK installation doesn't find JDK](http://stackoverflow.com/questions/4382178/android-sdk-installation-doesnt-find-jdk) - ['Must Override a Superclass Method' Errors after importing a project into Eclipse](http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) diff --git a/contents/android-sdk-installation-doesnt-find-jdk.md b/contents/android-sdk-installation-doesnt-find-jdk.md index 7b70797..117b823 100644 --- a/contents/android-sdk-installation-doesnt-find-jdk.md +++ b/contents/android-sdk-installation-doesnt-find-jdk.md @@ -28,3 +28,6 @@ - JAVA_HOME=C:/Program Files/Java/jdk1.8.0_11 - JRE_HOME=C:/Program Files/Java/jre8 - Path=%JAVA_HOME%;C:... + +stackoverflow链接: +http://stackoverflow.com/questions/4382178/android-sdk-installation-doesnt-find-jdk \ No newline at end of file From ca5550bd7fc8dc35aeca92c51d9d22a87792e50e Mon Sep 17 00:00:00 2001 From: giantray <51961070@qq.com> Date: 2016年8月24日 09:00:54 +0800 Subject: [PATCH 059/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B7=B2=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index e57f95e..624fcdb 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,6 @@ stackoverflow-Java-top-qa - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) - [How to generate a random alpha-numeric string?](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) -- [Comparing Java enum members: == or equals()?](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals) - [Failed to load the JNI shared Library (JDK)](http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk) - [What exactly is Apache Camel?](http://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel) - [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) From af7821226f4bab3ccf8f2b5e85ddbb1f327258c2 Mon Sep 17 00:00:00 2001 From: AcceptedBoy <972192420@qq.com> Date: 2016年8月28日 22:57:19 +0800 Subject: [PATCH 060/108] add->efficiency-of-java-double-brace-initialization.md --- ...ncy-of-java-double-brace-initialization.md | 202 ++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 contents/efficiency-of-java-double-brace-initialization.md diff --git a/contents/efficiency-of-java-double-brace-initialization.md b/contents/efficiency-of-java-double-brace-initialization.md new file mode 100644 index 0000000..6066b1c --- /dev/null +++ b/contents/efficiency-of-java-double-brace-initialization.md @@ -0,0 +1,202 @@ +## "Double Brace Initialization"的效率问题 + +#### 问题 + +`Double Brace Initialization`是java的隐藏特性,它有着如下诱人的语法: + +```java +Set flavors = new HashSet() {{ + add("vanilla"); + add("strawberry"); + add("chocolate"); + add("butter pecan"); +}}; +``` + +但是,这个特性听说不是很高效率,是否要限制一次性使用? + +#### 回答 + +当我使用匿名内部类时出现了如下的问题: + +```Auto +2009年05月27日 16:35 1,602 DemoApp21ドル.class +2009年05月27日 16:35 1,976 DemoApp210ドル.class +2009年05月27日 16:35 1,919 DemoApp211ドル.class +2009年05月27日 16:35 2,404 DemoApp212ドル.class +2009年05月27日 16:35 1,197 DemoApp213ドル.class + +/* snip */ + +2009年05月27日 16:35 1,953 DemoApp230ドル.class +2009年05月27日 16:35 1,910 DemoApp231ドル.class +2009年05月27日 16:35 2,007 DemoApp232ドル.class +2009年05月27日 16:35 926 DemoApp233ドル1ドル1ドル.class +2009年05月27日 16:35 4,104 DemoApp233ドル1ドル.class +2009年05月27日 16:35 2,849 DemoApp233ドル.class +2009年05月27日 16:35 926 DemoApp234ドル1ドル1ドル.class +2009年05月27日 16:35 4,234 DemoApp234ドル1ドル.class +2009年05月27日 16:35 2,849 DemoApp234ドル.class + +/* snip */ + +2009年05月27日 16:35 614 DemoApp240ドル.class +2009年05月27日 16:35 2,344 DemoApp25ドル.class +2009年05月27日 16:35 1,551 DemoApp26ドル.class +2009年05月27日 16:35 1,604 DemoApp27ドル.class +2009年05月27日 16:35 1,809 DemoApp28ドル.class +2009年05月27日 16:35 2,022 DemoApp29ドル.class +``` + +这是在我的一个简单应用中所产生的类信息。在这个应用中,使用了大量的匿名内部类,这些类会被单独地编译成`class`文件。 + +`Double Brace Initialization`是一个带有实例初始化块的匿名内部类。这就意味着每一个新的类的产生都会执行一次实例块,这样的目的通常是为了创建一个简单的对象。 + +java虚拟机在使用类之前需要去读取其classes信息,然后执行字节码校验等流程。所以为了保存这些`class`文件,所需要的磁盘空间会增大。 + +这个可以说是`Double Brace Initialization`的开销。所以尽量不要过分使用。 + +--- + +在java的介绍中,`Double Brace Initialization`有着如下的写法: + +```java +List list = new ArrayList() {{ + add("Hello"); + add("World!"); +}}; +``` + +看起来像是java的隐藏特性,其实它只是下面代码的一个重写: + +```java +List list = new ArrayList() { + + // 实例初始化块 + { + add("Hello"); + add("World!"); + } +}; +``` + +所以,它只是在匿名内部类中加上了实例初始化块而已。 + +--- + +Joshua Bloch希望以后的集合代码能够像这样简介: + +```java +List intList = [1, 2, 3, 4]; + +Set strSet = {"Apple", "Banana", "Cactus"}; + +Map truthMap = { "answer" : 42 }; +``` + +但目前还没有这样的语法。 + +--- + +实践 + +做一个简单的试验:创建1000个带着`"Hello"`和`"World!"`元素的`ArrayList` + +* 方法1:Double Brace Initialization + +``` +List l = new ArrayList() {{ + add("Hello"); + add("World!"); +}}; +``` + +* 方法2:初始化`ArrayList`并调用`add`方法 + +```java +List l = new ArrayList(); +l.add("Hello"); +l.add("World!"); +``` + +我修改了java的源文件使之能够为每种上述方法分别创建出1000个实例 + +* 方法1的测试 + +```java +class Test1 { + public static void main(String[] s) { + long st = System.currentTimeMillis(); + + List l0 = new ArrayList() {{ + add("Hello"); + add("World!"); + }}; + + List l1 = new ArrayList() {{ + add("Hello"); + add("World!"); + }}; + + /* snip */ + + List l999 = new ArrayList() {{ + add("Hello"); + add("World!"); + }}; + + System.out.println(System.currentTimeMillis() - st); + } +``` + +* 方法2的测试 + +```java +class Test2 { + public static void main(String[] s) { + long st = System.currentTimeMillis(); + + List l0 = new ArrayList(); + l0.add("Hello"); + l0.add("World!"); + + List l1 = new ArrayList(); + l1.add("Hello"); + l1.add("World!"); + + /* snip */ + + List l999 = new ArrayList(); + l999.add("Hello"); + l999.add("World!"); + + System.out.println(System.currentTimeMillis() - st); + } +} +``` + +然后得出了下面的测试时间: + +```Auto +Test1 Times (ms) Test2 Times (ms) +---------------- ---------------- + 187 0 + 203 0 + 203 0 + 188 0 + 188 0 + 187 0 + 203 0 + 188 0 + 188 0 + 203 0 +``` + +从上面我们可以看到,`Double Brace Initialization`平均时间花费了190ms左右。 +同时,另外一种方法平均只用了0ms。 + +所以,在第一个方法测试程序中,即`Double Brace Initialization`产生了1000个`class`文件。 + +## StackOverflow地址 + +[http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) \ No newline at end of file From 0ae910dfdc3afd14fb146fffb146c4dca5e8af17 Mon Sep 17 00:00:00 2001 From: bboylin Date: Thu, 1 Sep 2016 01:28:30 +0800 Subject: [PATCH 061/108] finished translating Why does this go into an infinite loop? --- .../why-does-this-go-into-an-infinite-loop.md | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 contents/why-does-this-go-into-an-infinite-loop.md diff --git a/contents/why-does-this-go-into-an-infinite-loop.md b/contents/why-does-this-go-into-an-infinite-loop.md new file mode 100644 index 0000000..7b8b6eb --- /dev/null +++ b/contents/why-does-this-go-into-an-infinite-loop.md @@ -0,0 +1,143 @@ +## 这段代码为什么陷入了死循环 + +### 问题 +我写了这样一段代码 + +```java +public class Tests { + public static void main(String[] args) throws Exception { + int x = 0; + while(x<3) { + x = x++; + System.out.println(x); + } + } +} +``` + +我们知道他应该只写x++或者x=x+1就行了,但是x=x++的情况下,x应该先赋值给自己,然后再增加1。为什么X的值一直是0呢? + +--更新 +
下面是字节码 + +```java +public class Tests extends java.lang.Object{ +public Tests(); + Code: + 0: aload_0 + 1: invokespecial #1; //Method java/lang/Object."":()V + 4: return + +public static void main(java.lang.String[]) throws java.lang.Exception; + Code: + 0: iconst_0 + 1: istore_1 + 2: iload_1 + 3: iconst_3 + 4: if_icmpge 22 + 7: iload_1 + 8: iinc 1, 1 + 11: istore_1 + 12: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; + 15: iload_1 + 16: invokevirtual #3; //Method java/io/PrintStream.println:(I)V + 19: goto 2 + 22: return + +} +``` + + +### 回答 + +一开始我用C#代码来解释,因为C#允许用"ref"关键字来实现int参数的引用传递,所以我决定用我google到的MutableInt类写的标准的java代码来模拟C#中ref关键字作用.我不知道这对我的解答是不是有帮助,我并不是一个专业的java开发者,我知道还有很多更符合语言习惯的方法去解释这个问题。 +也许我写一个函数来模拟x++的作用会解释得更清楚 + +```java +public MutableInt postIncrement(MutableInt x) { + int valueBeforeIncrement = x.intValue(); + x.add(1); + return new MutableInt(valueBeforeIncrement); +} +``` + +对不对?将传递的参数值加1然后返回原值,这就是后增操作符的定义。 +现在让我们看看在你的代码中是怎么执行的。 + +```java +MutableInt x = new MutableInt(); +x = postIncrement(x); +``` + +`postIncrement(x)`函数做了什么?x增加1,对,然后返回x加1之前的值,并且把该返回值赋给x。所以X被赋值的顺序是0,1,0。如果我们重写上面的代码会理解得更清楚。 + +```java +MutableInt x = new MutableInt(); // x is 0. +MutableInt temp = postIncrement(x); // Now x is 1, and temp is 0. +x = temp; // Now x is 0 again. +``` + +你定势地认为,将左边的X换个名称为y,"你能看到x先自增1,然后赋值给了y",这一时也让我有点困惑。bi那个不是x被赋值给y,而是x(自增)之前的值被赋给y.事实上,把左边x变量名改成y结果也没什么不同。 + +```java +MutableInt x = new MutableInt(); // x is 0. +MutableInt y = new MutableInt(); // y is 0. +MutableInt temp = postIncrement(x); // Now x is 1, and temp is 0. +y = temp; // y is still 0. +``` + +可见,x=x++并没有改变x的值,只是让x依次被赋值为x0,x0+1,x0。 + +更新:你可能会怀疑在自增过程中x并没有被赋值为1,下面通过一个demo来解释确实x存在赋值为1的过程。 +demo中调用了x=x++;同时另外开了一个单独的线程不断输出x的值. + +```java +public class Main { + public static volatile int x = 0; + + public static void main(String[] args) { + LoopingThread t = new LoopingThread(); + System.out.println("Starting background thread..."); + t.start(); + + while (true) { + x = x++; + } + } +} + +class LoopingThread extends Thread { + public @Override void run() { + while (true) { + System.out.println(Main.x); + } + } +} +``` + +下面是程序的部分输出,0和1不规则的出现。 + +``` +Starting background thread... +0 +0 +1 +1 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +1 +0 +1 +``` + + +stackoverflow链接: +[http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) From 3105d5c888362c83c3e5ccbf388b318e5ceb22ed Mon Sep 17 00:00:00 2001 From: sunzhongsheng <1294477941@qq.com> Date: 2016年9月26日 19:39:09 +0800 Subject: [PATCH 062/108] no message --- ...-math-round0-49999999999999994-return-1.md | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 contents/why-does-math-round0-49999999999999994-return-1.md diff --git a/contents/why-does-math-round0-49999999999999994-return-1.md b/contents/why-does-math-round0-49999999999999994-return-1.md new file mode 100644 index 0000000..6da947a --- /dev/null +++ b/contents/why-does-math-round0-49999999999999994-return-1.md @@ -0,0 +1,96 @@ +# 为什么数学函数Math.round(0.49999999999999994) 返回 1 + +tags:stackoverflow-java-top-qa + +--- + +###问题 +通过下面的程序你可以看出来,对于任意一个比0.5略小的都是舍去小数向下取整,只有0.5是例外. + +```java +for (int i = 10; i>= 0; i--) { + long l = Double.doubleToLongBits(i + 0.5); + double x; + do { + x = Double.longBitsToDouble(l); + System.out.println(x + " rounded is " + Math.round(x)); + l--; + } while (Math.round(x)> i); +} +``` + +输出为: + +``` +10.5 rounded is 11 +10.499999999999998 rounded is 10 +9.5 rounded is 10 +9.499999999999998 rounded is 9 +8.5 rounded is 9 +8.499999999999998 rounded is 8 +7.5 rounded is 8 +7.499999999999999 rounded is 7 +6.5 rounded is 7 +6.499999999999999 rounded is 6 +5.5 rounded is 6 +5.499999999999999 rounded is 5 +4.5 rounded is 5 +4.499999999999999 rounded is 4 +3.5 rounded is 4 +3.4999999999999996 rounded is 3 +2.5 rounded is 3 +2.4999999999999996 rounded is 2 +1.5 rounded is 2 +1.4999999999999998 rounded is 1 +0.5 rounded is 1 +0.49999999999999994 rounded is 1 +0.4999999999999999 rounded is 0 + +``` +*_译者注:请看输出的最后两行,0.49999999999999994的输出为1,而0.49999999999999999的输出为0* + +我使用的版本是 Java 6 update 31 + +### 回答 +**总结** + +在 Java 6(或者之前的版本),round(x)是用floor(x+0.5)实现的.1 这是一个规范上的bug,恰恰是在这种病理条件下.2Java 7 不再使用这个有问题的实现了. + +**问题** + +0.5+0.49999999999999994 在double的精度下的结果是1 +```java +static void print(double d) { + System.out.printf("%016x\n", Double.doubleToLongBits(d)); +} + +public static void main(String args[]) { + double a = 0.5; + double b = 0.49999999999999994; + + print(a); // 3fe0000000000000 + print(b); // 3fdfffffffffffff + print(a+b); // 3ff0000000000000 + print(1.0); // 3ff0000000000000 +} +``` +这是因为0.49999999999999994的指数比0.5的指数小,所以当它们两个相加时,0.49999999999999994的原数就会发生移位,然后最小精度单位(unit of least precision)/最后置单位(unit of last place)相应的变大了. + +**解决方案** + +自从Java 7以来,OpenJDK(举个栗子)实现如下4: + +```java +public static long round(double a) { + if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5 + return (long)floor(a + 0.5d); + else + return 0; +} +``` +1. [http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round%28double%29](http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round%28double%29) +2. [http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675](http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675) (credits to @SimonNickerson for finding this) +3. [http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round%28double%29](http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round%28double%29) +4. [http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/Math.java#Math.round%28double%29](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/Math.java#Math.round%28double%29) + +### stackoverflow原文链接:[http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) \ No newline at end of file From f2be3e883e6ebe26dcb8dc9f97710a39cf231cec Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月27日 18:12:03 +0800 Subject: [PATCH 063/108] first edition --- .../how-to-create-a-generic-array2-in-java.md | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 contents/how-to-create-a-generic-array2-in-java.md diff --git a/contents/how-to-create-a-generic-array2-in-java.md b/contents/how-to-create-a-generic-array2-in-java.md new file mode 100644 index 0000000..b46d670 --- /dev/null +++ b/contents/how-to-create-a-generic-array2-in-java.md @@ -0,0 +1,77 @@ +如何创建一个java泛型数组 +问题: +由于Java泛型的实现机制,你不能这样写代码: +pulic class GenSet{ + private E a[]; + public GetSet(){ + a=new E[INITIAL_ARRAY_LENGTH]; //error:generic array creation + } +} +在保证类型安全的情况下,我该如何实现创建一个Java泛型数组? +我在一个Java论坛上看到是这样解决的: +import java.lang.reflect.Array; + +class Stack { + public Stack(Class clazz, int capacity) { + array = (T[])Array.newInstance(clazz, capacity); + } + + private final T[] array; +} +但我不懂发生了什么。有人能帮我吗? + +回答: +在回答之前,我得问你一个问题,你的GetSet是"checked"还是"unchecked"? +什么意思呢? +Checked的话,是强类型。GetSet明确地知道包含了什么类型的对象。 +比如,当要传递不是E类型的实参时,它的构造器会被Class引数明确地调用,方法会抛出一个异常。参阅Collections.checkedCollection。 +在这种情况下,你应该这样写: +public class GenSet { + + private E[] a; + + public GenSet(Class c, int s) { + // Use Array native method to create array + // of a type only known at run time + @SuppressWarnings("unchecked") + final E[] a = (E[]) Array.newInstance(c, s); + this.a = a; + } + + E get(int i) { + return a[i]; + } +} +Unchecked的话:弱类型。实际上要传递任何对象的实参时 +是没有类型检查的。 +在这种情况下,你应当这样写: +public class GenSet { + + private Object[] a; + + public GenSet(int s) { + a = new Object[s]; + } + + E get(int i) { + @SuppressWarnings("unchecked") + final E e = (E) a[i]; + return e; + } +} +注意数组里的元素类型应当是可擦除的形参。 +public class GenSet { // E has an upper bound of Foo + + private Foo[] a; // E erases to Foo, so use Foo[] + + public GenSet(int s) { + a = new Foo[s]; + } + + ... +} +所有的这些结果来自Java一个有名,存心,不足的泛型:它通过使用 +erasure实现,所以"泛型"类在运行时创建是不知道它的实参类型的, +所以不能提供类型安全,除非某些明确的机制(比如类型检查)已经实现了。 +StackOverflow地址: +http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java \ No newline at end of file From 12c00b74efb1dab2315f3d09f8ae0ed1fe4034fb Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月27日 23:59:39 +0800 Subject: [PATCH 064/108] unfinished --- contents/what-is-the-equivalent-of-the-c++pair-in-java.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 contents/what-is-the-equivalent-of-the-c++pair-in-java.md diff --git a/contents/what-is-the-equivalent-of-the-c++pair-in-java.md b/contents/what-is-the-equivalent-of-the-c++pair-in-java.md new file mode 100644 index 0000000..250f2ef --- /dev/null +++ b/contents/what-is-the-equivalent-of-the-c++pair-in-java.md @@ -0,0 +1,6 @@ +Java里什么是与C++的Pair相等的? +问题: +Java里没有Pair是不是一个好理由?那什么会和C++这个结构相等呢?似乎1.6版本提供了一些类似的(比如AbstractMap.SimpleEntry),但这看起来很费解。 + +回答: + From 9c52fc0deee0fbdc985e87a5c7169d81f5968504 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月28日 08:25:26 +0800 Subject: [PATCH 065/108] first-commit --- contents/what-is-the-equivalent-of-the-c++pair-in-java.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/contents/what-is-the-equivalent-of-the-c++pair-in-java.md b/contents/what-is-the-equivalent-of-the-c++pair-in-java.md index 250f2ef..377cd9e 100644 --- a/contents/what-is-the-equivalent-of-the-c++pair-in-java.md +++ b/contents/what-is-the-equivalent-of-the-c++pair-in-java.md @@ -3,4 +3,10 @@ Java里什么是与C++的Pair相等的? Java里没有Pair是不是一个好理由?那什么会和C++这个结构相等呢?似乎1.6版本提供了一些类似的(比如AbstractMap.SimpleEntry),但这看起来很费解。 回答: +在comp.lang.java.help的一个论坛上,Hunter Gratzner对于java的Pair结构给出了一些论点。主要的论点是Pair类不能传达出两个值的关系的语义(你怎么能知道第一和第二代表什么?) +一个最好的校验是写一个非常简单的类,像Mike建议的,每一个应用上的pair类,Map.Entry都能很好的取代。 +总的来说,我建议是最好是一个Position(x,y)类,一个Range(begin,end)和一个Entry(key,value)类,而不是一个不能告诉我应该怎么做的广泛Pair(first,second)类。 + +stackoverflow的地址: +http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java From 3688c5e159282e29b826a1f148652d1c3b9708b1 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月29日 19:46:20 +0800 Subject: [PATCH 066/108] =?UTF-8?q?=E7=AC=AC=E4=B8=89=E7=AF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Eclipse-set-maximun-line-length-for-auto-formatting.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 contents/Eclipse-set-maximun-line-length-for-auto-formatting.md diff --git a/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md b/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md new file mode 100644 index 0000000..b1f8579 --- /dev/null +++ b/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md @@ -0,0 +1,4 @@ +为自动代码调整设置最大的行数? +问题:我正在学习Java。如果我在Eclipse Helios里使用ctrl+shift+f的组合键,它会自动调整我的代码。一定程度下,它会改变行数。我想增加行数的最大值。应该怎么做? + +回答,在偏好设置里,分别点击Java->Code Style->Fomatter->edit,在菜单栏Line Wrapping下会有行的宽度选择(Maximun line width).你将需要编辑你的代码轮廓。 \ No newline at end of file From 8d0b2d8ef1a2e8528d4a8f1fd1dd42f94720cab2 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月30日 21:07:24 +0800 Subject: [PATCH 067/108] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E7=AF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../failed-to-load-the-JNI-shared-library(JDK).md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 contents/failed-to-load-the-JNI-shared-library(JDK).md diff --git a/contents/failed-to-load-the-JNI-shared-library(JDK).md b/contents/failed-to-load-the-JNI-shared-library(JDK).md new file mode 100644 index 0000000..6ac55e2 --- /dev/null +++ b/contents/failed-to-load-the-JNI-shared-library(JDK).md @@ -0,0 +1,15 @@ +加载JNI共享库失败(JDK) +问题:当我试图打开Eclipse时,会弹出一个提示写着: +Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`. +然后,Eclipse会强制关闭。 +我做了以下几点: +·我检查那个路径有没有存在什么,真的有存在。 +·我的Eclipse和Java SE Development Kit都是64位的。我检查我的系统,它能处理64位。 +·我也在Google和Stack Overflow搜索解决方法,我找到唯一的方法是下载一个32位版本的JDK和Eclipse。 +下载32位版本是我没办法下的办法。但还有其他的解决方法吗? + +回答: +你需要一个三件套: +·64位的操作系统 +·64位的Java +·64位的Eclipse From d4cacdbca11876fa81af0002e910dee540672870 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月30日 21:09:24 +0800 Subject: [PATCH 068/108] Update failed-to-load-the-JNI-shared-library(JDK).md --- contents/failed-to-load-the-JNI-shared-library(JDK).md | 1 + 1 file changed, 1 insertion(+) diff --git a/contents/failed-to-load-the-JNI-shared-library(JDK).md b/contents/failed-to-load-the-JNI-shared-library(JDK).md index 6ac55e2..bd489d9 100644 --- a/contents/failed-to-load-the-JNI-shared-library(JDK).md +++ b/contents/failed-to-load-the-JNI-shared-library(JDK).md @@ -13,3 +13,4 @@ Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`. ·64位的操作系统 ·64位的Java ·64位的Eclipse + From fa4a9731131c104e5673b86e355c0fef33570cdc Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月30日 21:10:35 +0800 Subject: [PATCH 069/108] Update failed-to-load-the-JNI-shared-library(JDK).md --- contents/failed-to-load-the-JNI-shared-library(JDK).md | 1 + 1 file changed, 1 insertion(+) diff --git a/contents/failed-to-load-the-JNI-shared-library(JDK).md b/contents/failed-to-load-the-JNI-shared-library(JDK).md index bd489d9..b60b2cd 100644 --- a/contents/failed-to-load-the-JNI-shared-library(JDK).md +++ b/contents/failed-to-load-the-JNI-shared-library(JDK).md @@ -14,3 +14,4 @@ Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`. ·64位的Java ·64位的Eclipse + From 5e57dac278aa777df983177aee4ab5a9ba446d81 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月30日 21:47:50 +0800 Subject: [PATCH 070/108] =?UTF-8?q?=E4=B8=BA=E4=BB=80=E4=B9=88=E4=B8=8D?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "345円244円207円345円277円230円.md" | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 "345円244円207円345円277円230円.md" diff --git "a/345円244円207円345円277円230円.md" "b/345円244円207円345円277円230円.md" new file mode 100644 index 0000000..e69de29 From d72929b775f3dccf76ad3e48e8539e6d8c322fb1 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年9月30日 21:55:47 +0800 Subject: [PATCH 071/108] =?UTF-8?q?Update=20=E5=A4=87=E5=BF=98.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "345円244円207円345円277円230円.md" | 1 + 1 file changed, 1 insertion(+) diff --git "a/345円244円207円345円277円230円.md" "b/345円244円207円345円277円230円.md" index e69de29..c2e3070 100644 --- "a/345円244円207円345円277円230円.md" +++ "b/345円244円207円345円277円230円.md" @@ -0,0 +1 @@ +就是不行了 From cc14bc87d3125c4f1c8950286caa4232073188e7 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: Sun, 2 Oct 2016 21:46:05 +0800 Subject: [PATCH 072/108] =?UTF-8?q?=E7=AC=AC=E4=BA=94=E7=AF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/lookup-enum-by-string-value (2).md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 contents/lookup-enum-by-string-value (2).md diff --git a/contents/lookup-enum-by-string-value (2).md b/contents/lookup-enum-by-string-value (2).md new file mode 100644 index 0000000..34db1b2 --- /dev/null +++ b/contents/lookup-enum-by-string-value (2).md @@ -0,0 +1,13 @@ +如何将枚举转换成数组 +问题: +假设我有一个枚举类是这样的: +public enum Blah { + A, B, C, D +} +我想要将枚举类的值转化成一个数组,比如"A"怎么可能是Blah.A.怎么有可能做到这点?我需要Enum.valueOf()这个方法吗?如果是这样,我应该怎么用他? + +回答: +是的,Blah.valuOf("A")将会给你Blah.A。 +valueOf()和values()这些静态方法是在编译时创建的,而且不会出现在源代码里。不过他们确实有出现在Javadoc,比如Dialog.ModalityType有这两个方法。 +stackoverflow链接: +http://stackoverflow.com/questions/604424/lookup-enum-by-string-value From deb7717cc691f4f45218888328c6260fb514a3fc Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: Sun, 2 Oct 2016 22:05:25 +0800 Subject: [PATCH 073/108] =?UTF-8?q?=E7=AC=AC=E4=BA=94=E7=AF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/lookup-enum-by-string-value2.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 contents/lookup-enum-by-string-value2.md diff --git a/contents/lookup-enum-by-string-value2.md b/contents/lookup-enum-by-string-value2.md new file mode 100644 index 0000000..34db1b2 --- /dev/null +++ b/contents/lookup-enum-by-string-value2.md @@ -0,0 +1,13 @@ +如何将枚举转换成数组 +问题: +假设我有一个枚举类是这样的: +public enum Blah { + A, B, C, D +} +我想要将枚举类的值转化成一个数组,比如"A"怎么可能是Blah.A.怎么有可能做到这点?我需要Enum.valueOf()这个方法吗?如果是这样,我应该怎么用他? + +回答: +是的,Blah.valuOf("A")将会给你Blah.A。 +valueOf()和values()这些静态方法是在编译时创建的,而且不会出现在源代码里。不过他们确实有出现在Javadoc,比如Dialog.ModalityType有这两个方法。 +stackoverflow链接: +http://stackoverflow.com/questions/604424/lookup-enum-by-string-value From ca3ff7f1da208fde6433569629491247774272e3 Mon Sep 17 00:00:00 2001 From: Lianghui2 <2915057607@qq.com> Date: 2016年10月15日 23:30:40 +0800 Subject: [PATCH 074/108] woqu --- contents/lookup-enum-by-string-value (2).md | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 contents/lookup-enum-by-string-value (2).md diff --git a/contents/lookup-enum-by-string-value (2).md b/contents/lookup-enum-by-string-value (2).md deleted file mode 100644 index 34db1b2..0000000 --- a/contents/lookup-enum-by-string-value (2).md +++ /dev/null @@ -1,13 +0,0 @@ -如何将枚举转换成数组 -问题: -假设我有一个枚举类是这样的: -public enum Blah { - A, B, C, D -} -我想要将枚举类的值转化成一个数组,比如"A"怎么可能是Blah.A.怎么有可能做到这点?我需要Enum.valueOf()这个方法吗?如果是这样,我应该怎么用他? - -回答: -是的,Blah.valuOf("A")将会给你Blah.A。 -valueOf()和values()这些静态方法是在编译时创建的,而且不会出现在源代码里。不过他们确实有出现在Javadoc,比如Dialog.ModalityType有这两个方法。 -stackoverflow链接: -http://stackoverflow.com/questions/604424/lookup-enum-by-string-value From b58ab999f79c28252274938b1e32b75d385e71e3 Mon Sep 17 00:00:00 2001 From: Akuma Date: 2016年10月20日 14:57:53 +0800 Subject: [PATCH 075/108] fix a typo --- ...examples-of-gof-design-patterns-in-javas-core-libraries.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/examples-of-gof-design-patterns-in-javas-core-libraries.md b/contents/examples-of-gof-design-patterns-in-javas-core-libraries.md index 6ea5bdf..97ce66b 100644 --- a/contents/examples-of-gof-design-patterns-in-javas-core-libraries.md +++ b/contents/examples-of-gof-design-patterns-in-javas-core-libraries.md @@ -54,7 +54,7 @@ ### [装饰模式](http://en.wikipedia.org/wiki/Decorator_pattern) -- [java.io.InputStream](http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html),[OutputStream](http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html),[Reader](http://docs.oracle.com/javase/6/docs/api/java/io/Reader.html) 和 [Writer](http://docs.oracle.com/javase/6/docs/api/java/io/Writer.html) 的所有资料都有一个使用 InputStream,OutputStream,Reader,Writer 的构造器 +- [java.io.InputStream](http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html), [OutputStream](http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html), [Reader](http://docs.oracle.com/javase/6/docs/api/java/io/Reader.html) 和 [Writer](http://docs.oracle.com/javase/6/docs/api/java/io/Writer.html) 的所有子类都有一个使用 InputStream, OutputStream, Reader, Writer 的构造器 - [java.util.Collections](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html) 中的 [checkedXXX()](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29), [synchronizedXXX()](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedCollection%28java.util.Collection%29) 和 [unmodifiableXXX()](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#unmodifiableCollection%28java.util.Collection%29) 方法 - [javax.servlet.http.HttpServletRequestWrapper](http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequestWrapper.html) 和 [HttpServletResponseWrapper](http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponseWrapper.html) @@ -148,4 +148,4 @@ - stackoverflow原址: -http://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries \ No newline at end of file +http://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries From 941d6da8fbf444eeb22aeb1f286da4a6ca9125ba Mon Sep 17 00:00:00 2001 From: jinzhencheng Date: 2016年10月30日 14:07:20 +0800 Subject: [PATCH 076/108] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86<<=e5=bd=93?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E9=A1=B9=E7=9B=AE=E5=88=B0eclipse=E6=97=B6?= =?UTF-8?q?=E6=8A=A5=E9=94=99=E3=80=8B=E7=9A=84=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...s-after-importing-a-project-into-eclips.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 contents/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips.md diff --git a/contents/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips.md b/contents/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips.md new file mode 100644 index 0000000..723403f --- /dev/null +++ b/contents/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips.md @@ -0,0 +1,35 @@ + +##问题 +大多数情况下,当我重新导入项目到eclipse的时候,我重写的方法都不能被正确格式化,导致这样的错误: +> The method must override a superclass method. + +需要说明的是这是一个Android项目,不知道什么原因,方法的参数被篡改了,因此,我不得不手动的把他们改回来。 +例如: +```java +list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { + //这儿的参数名是正确的 + public void onCreateContextMenu(ContextMenu menu, View v, + ContextMenuInfo menuInfo) { + } +}); +``` +初始化的时候被篡改成了这样: +```java +list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { + //这儿的参数被篡改成了这样 + public void onCreateContextMenu(ContextMenu arg1, View arg2, + ContextMenuInfo arg3) { + } +}); +``` +奇怪的是,如果我移除我的代码并使用eclipse自动创建方法的话,它还是会是相同的参数(被篡改的)。因此,我真不知道那儿的问题,它本应该自动格式化代码的。 +要是手动的去修改被篡改的参数名,那是一个非常痛苦的过程。要是有人能解释为什么会出现这样的情况以及怎样去解决它,我感激不尽。 +是不是因为我格式化的这个方法,是另一个方法里面的参数而导致的这样的问题呢? + +##回答 +Eclipse的默认执行环境是java 1.5况且你使用了类的声明接口方法(在java 1.6中能使用@Ovrride注释,但是在java 1.5中一个方法只能重写父类的方法) + +打开你的项目,然后找到preference并且设置java的编译版本为1.6,同时也确保你的eclipse是使用JRE 1.6 来执行你的程序的。 + +Stack Overflow原地址:http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips + From 62d40b18bba335a745a7ffa6ab99d8445dc5039c Mon Sep 17 00:00:00 2001 From: jinzhencheng Date: 2016年10月31日 17:31:43 +0800 Subject: [PATCH 077/108] update 'Sort ArrayList of custom Objects by property' --- ...arraylist-of-custom-objects-by-property.md | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 contents/sort-arraylist-of-custom-objects-by-property.md diff --git a/contents/sort-arraylist-of-custom-objects-by-property.md b/contents/sort-arraylist-of-custom-objects-by-property.md new file mode 100644 index 0000000..5c279a4 --- /dev/null +++ b/contents/sort-arraylist-of-custom-objects-by-property.md @@ -0,0 +1,75 @@ + + +##通过对象属性对常规对象的ArrayList进行排序 + +###问题 +我读过使用Comparator对常规类的ArrayList进行排序的示例,但是它们大多数使用comparedTo(),据我了解这是一个对字符串进行操作的方法。 +我想要对一个由常规对象构成的ArrayList,通过它的属性(一个Date对象,getStartDate())对ArrayList进行排序。通常情况下我这样比较它们: +```java +item1.getStartDate().before(item2.getStartDate()) +``` +所以我能不能像下面一样: +```java +public class CustomComparator { + public boolean compare(Object object1, Object object2) { + return object1.getStartDate().before(object2.getStartDate()); + } +} + +public class RandomName { + ... + Collections.sort(Database.arrayList, new CustomComparator); + ... +} +``` + +###回答 + 以前Date声明了Comparable,它有一个像处理字符串操作那样的compareTo方法。因此你可以这样: +```java +public class CustomComparator implements Comparator { + @Override + public int compare(MyObject o1, MyObject o2) { + return o1.getStartDate().compareTo(o2.getStartDate()); + } +} +``` +这儿的compare()方法必须返回int,所以不能像你预期那样直接返回boolean. +你的代码看起来应该是这样: +```java +Collections.sort(Database.arrayList, new CustomComparator()); +``` +如果你不需要重复使用comparetor的话,一种简单的方法是,把它写成一个内部类的样子: +```java +Collections.sort(Database.arrayList, new Comparator() { + @Override + public int compare(MyObject o1, MyObject o2) { + return o1.getStartDate().compareTo(o2.getStartDate()); + } +}); +``` +自java8 开始,你可以使用lambda表达式一种简洁的方式来写Comparator() +```java +Collections.sort(Database.arrayList, + (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate())); +``` +并且List有一个sort(Comparator)方法,所以你可以进一步简化它 +```java + +Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate())); +``` +这是一种司空见惯的方法,使用Comparable为一个类创建一个Comprator +```java +Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate)); +All of these are equivalent forms. +``` + +stackoverflow原地址:http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property + + + + + + + + + From 0e1260d652a9ecbf2b055794a5429de05eaad863 Mon Sep 17 00:00:00 2001 From: lcs1795192 <1845251476@qq.com> Date: 2017年1月17日 14:48:36 +0800 Subject: [PATCH 078/108] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=AC=AC=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ses-for-android-usermanager-isuseragoat.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 contents/proper-use-cases-for-android-usermanager-isuseragoat.md diff --git a/contents/proper-use-cases-for-android-usermanager-isuseragoat.md b/contents/proper-use-cases-for-android-usermanager-isuseragoat.md new file mode 100644 index 0000000..06301bd --- /dev/null +++ b/contents/proper-use-cases-for-android-usermanager-isuseragoat.md @@ -0,0 +1,38 @@ +##安卓中"UserManger.isUserAGoat()"的合适案例? + +###问题描述: +我正在看在安卓4.2里介绍的新API。当看到"UserManger"类时,我遇到了如下的"method": +public boolean isUserAGoat() +Used to determine whether the user making this call is subject to teleportations. + +Returns whether the user making this call is a goat. +这个应该怎样使用和什么时候使用? + +###回答: +根据他们的资料,在API21前,这个"method"用来返回"false" +/** + * Used to determine whether the user making this call is subject to + * teleportations. + * @return whether the user making this call is a goat + */ +public boolean isUserAGoat() { + return false; +} +看起来这个"method"对我们开发者没有真正的用途。一些人之前认为它可能是个复活节彩蛋。 +再次编辑: +在API21它改为判断是否存在有包"com.coffeestainstudios.goatsimulator"的已安装app。 +/** + * Used to determine whether the user making this call is subject to + * teleportations. + * + *

As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can + * now automatically identify goats using advanced goat recognition technology.

+ * + * @return Returns true if the user making this call is a goat. + */ +public boolean isUserAGoat() { + return mContext.getPackageManager() + .isPackageAvailable("com.coffeestainstudios.goatsimulator"); +} + +[stackoverflow链接:Proper use cases for Android UserManager.isUserAGoat()](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) From 3fc6af09e6bad5bfa6d1f75a65f8f1852612562b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=B0=8F=E8=BF=87?= <2638334066@qq.com> Date: Sun, 5 Mar 2017 23:17:13 +0800 Subject: [PATCH 079/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86convert-a-st?= =?UTF-8?q?ring-to-an-enum-in-java=EF=BC=8C=E5=A2=9E=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=E4=B8=80=E7=A7=8D=E5=B8=B8=E7=94=A8=E5=9B=9E=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增加的其他回答,在编程中更加常用,建议补充上。 --- .../convert-a-string-to-an-enum-in-java.md | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/contents/convert-a-string-to-an-enum-in-java.md b/contents/convert-a-string-to-an-enum-in-java.md index 5e11958..d9474b9 100644 --- a/contents/convert-a-string-to-an-enum-in-java.md +++ b/contents/convert-a-string-to-an-enum-in-java.md @@ -19,6 +19,38 @@ Enum.valueOf()是否能实现以上目的,如果是,那我如何使用? ### 其他答案 +当文本和枚举值不同时,可以采用这种方式: +```java +public enum Blah { + A("text1"), + B("text2"), + C("text3"), + D("text4"); + + private String text; + + Blah(String text) { + this.text = text; + } + + public String getText() { + return this.text; + } + + public static Blah fromString(String text) { + for (Blah b : Blah.values()) { + if (b.text.equalsIgnoreCase(text)) { + return b; + } + } + return null; + } +} +``` +fromString方法中,throw new IllegalArgumentException("No constant with text " + text + " found") 会比直接返回null更优秀. + +### 其他答案 + 我有一个挺赞的工具方法: ```java /** @@ -47,4 +79,4 @@ public static MyEnum fromString(String name) { } ``` -stackoverflow链接:http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java \ No newline at end of file +stackoverflow链接:http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java From 7aa258eba9165190942f7066c4f9745a11ec68ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=B0=8F=E8=BF=87?= <2638334066@qq.com> Date: Sun, 5 Mar 2017 23:25:36 +0800 Subject: [PATCH 080/108] =?UTF-8?q?Convert=20a=20String=20to=20an=20enum?= =?UTF-8?q?=20in=20Java=20=E9=97=AE=E9=A2=98=E5=9C=A8=E4=B8=80=E5=B9=B4?= =?UTF-8?q?=E5=89=8D=E5=B7=B2=E8=A2=AB=E5=9B=9E=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 该问题已被回答,建议更新Read.md - [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 624fcdb..dbf9fd3 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,6 @@ stackoverflow-Java-top-qa ### 待翻译问题链接(还剩x问题) - [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) -- [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) - ['Must Override a Superclass Method' Errors after importing a project into Eclipse](http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) From 5e42d2487b8e35815568c9888c433145a3789153 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=B0=8F=E8=BF=87?= <2638334066@qq.com> Date: Mon, 6 Mar 2017 01:05:22 +0800 Subject: [PATCH 081/108] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E4=BA=86apache-camel?= =?UTF-8?q?=E6=98=AF=E4=BB=80=E4=B9=88=E7=9A=84=E9=97=AE=E9=A2=98=E5=9B=9E?= =?UTF-8?q?=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1.创建了what-exactly-is-apache-camel.md 2.翻译问题和答案 3.增加了术语解释 4.对问题的通俗理解 --- contents/what-exactly-is-apache-camel.md | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 contents/what-exactly-is-apache-camel.md diff --git a/contents/what-exactly-is-apache-camel.md b/contents/what-exactly-is-apache-camel.md new file mode 100644 index 0000000..b2b3931 --- /dev/null +++ b/contents/what-exactly-is-apache-camel.md @@ -0,0 +1,36 @@ +### 问题描述 + +我不明白Camel到底是干什么的. +希望你能在101字以内介绍一下Camel: + 它到底是什么? + 如何在java中使用它? + 它是和服务器相关的么? + 它是一个独立的程序? +请解释一下Camel是什么. + +### 答案 +如果你有5-10分钟时间,我建议你读一下Jonathan Anstey关于Apache Camel的文章.这是一篇非常棒的文章,简要的介绍了一些Apache Camel的概念,以及用java实现了一个 +实例.Jonathan Anstey是这样描述的: +Apache Camel是一个开源的Java框架,其整合的目的主要是为了使开发人员更容易、方便的开发程序.它提供了如下内容: + +(1)所有被广泛使用的`企业集成模式`的具体实现(`EIPs`) + +(2)连接不同的数据传输和API + +(3)容易使用`领域特定语言(DSL)`建立EIPs和高效的数据传输 + +### 术语解析 + +`EIPs`:企业集成模式的简称,使用消息传递进行企业应用集成,比如消息中间件,将不同程序之间连接在一起. + +`DSL`:DSL编程又称为声明式编程,DSL是在模型之上建立的一种更加灵活的对模型化的理解和使用方式,通俗点说你只需要告诉程序你想要什么,不必每一步都指挥它如何 +执行,SQL语句就是其中的代表. + +### 通俗点讲 + +_Camel:将数据从一方获得,该数据可以是消息、文件流、JSON的多种形式的数据,然后处理,再发送,整合了多种数据获取、处理、发送方式,方便开发者使用_ + + +stackoverflow链接 +http://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel +_译者:[王小过](https://github.com/whp1473)_ From 9ceec4f12a4e0f96fbbb8b8f57179adacf5df6fd Mon Sep 17 00:00:00 2001 From: RWBUPT <1291839723@qq.com> Date: Thu, 9 Mar 2017 20:40:07 +0800 Subject: [PATCH 082/108] Create why-does-math.round-(0.49999999999999994)-return-1.md --- ...th.round-(0.49999999999999994)-return-1.md | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 contents/why-does-math.round-(0.49999999999999994)-return-1.md diff --git a/contents/why-does-math.round-(0.49999999999999994)-return-1.md b/contents/why-does-math.round-(0.49999999999999994)-return-1.md new file mode 100644 index 0000000..fb7bf35 --- /dev/null +++ b/contents/why-does-math.round-(0.49999999999999994)-return-1.md @@ -0,0 +1,92 @@ +##为什么Math.round(0.49999999999999994)返回1? + +###问题描述: + +在下面的程序中你可以看到每个稍微比.5小的值都被向下舍入了,除了`0.5`那个。 + +``` +for (int i = 10; i>= 0; i--) { + long l = Double.doubleToLongBits(i + 0.5); + double x; + do { + x = Double.longBitsToDouble(l); + System.out.println(x + " rounded is " + Math.round(x)); + l--; + } while (Math.round(x)> i); +} +``` +输出 +``` +10.5 rounded is 11 +10.499999999999998 rounded is 10 +9.5 rounded is 10 +9.499999999999998 rounded is 9 +8.5 rounded is 9 +8.499999999999998 rounded is 8 +7.5 rounded is 8 +7.499999999999999 rounded is 7 +6.5 rounded is 7 +6.499999999999999 rounded is 6 +5.5 rounded is 6 +5.499999999999999 rounded is 5 +4.5 rounded is 5 +4.499999999999999 rounded is 4 +3.5 rounded is 4 +3.4999999999999996 rounded is 3 +2.5 rounded is 3 +2.4999999999999996 rounded is 2 +1.5 rounded is 2 +1.4999999999999998 rounded is 1 +0.5 rounded is 1 +0.49999999999999994 rounded is 1 +0.4999999999999999 rounded is 0 +``` +我使用 Java 6 update 31。 + +###回答: + +**总结** + +在Java 6中(而且很可能更早),`round x`以`floor(x+0.5)`的方式执行[1]。这是一个规则上的bug,它恰好会导致这样一种不合道理的情况[2]。Java 7不再授权这种分离的执行方式[3]。 + +**问题** + +0.5+0.49999999999999994在双精度数中正好表示1: +``` +static void print(double d) { + System.out.printf("%016x\n", Double.doubleToLongBits(d)); +} + +public static void main(String args[]) { + double a = 0.5; + double b = 0.49999999999999994; + + print(a); // 3fe0000000000000 + print(b); // 3fdfffffffffffff + print(a+b); // 3ff0000000000000 + print(1.0); // 3ff0000000000000 +} +``` +这是因为0.49999999999999994有一个比0.5小的指数,所以它们相加时,它的尾数被移位了,ULP(ULP表示现有数值最后一位代表的最小数值单位,小于ULP的数值将无法累加到现有数值)变的更大。 + +**解决方法** + +从Java 7开始,OpenJDK(如下例)这样执行它(round函数)[4]。 +``` +public static long round(double a) { + if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5 + return (long)floor(a + 0.5d); + else + return 0; +} +``` +[1] http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round%28double%29 + +[2] http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675 (credits to @SimonNickerson for finding this) + +[3] http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round%28double%29 + +[4] http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/Math.java#Math.round%28double%29 + + +[stackoverflow链接:Why does Math.round(0.49999999999999994) return 1?](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) From a58d15e95d537f66caaa5c29a252b7e901f96e9e Mon Sep 17 00:00:00 2001 From: mysterin Date: 2017年4月10日 16:05:34 +0800 Subject: [PATCH 083/108] =?UTF-8?q?=E4=BF=AE=E6=94=B9stackoverflow?= =?UTF-8?q?=E7=9A=84=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来的链接是指向到so回答的第二页,打开过去并不是原答案所在,需要返回第一页才能看到原答案。 --- contents/avoiding-null-statements-in-java.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/avoiding-null-statements-in-java.md b/contents/avoiding-null-statements-in-java.md index aab0bc7..c2a1348 100644 --- a/contents/avoiding-null-statements-in-java.md +++ b/contents/avoiding-null-statements-in-java.md @@ -99,4 +99,4 @@ ParserFactory.getParser().findAction(someInput).doSomething(); - 如果你想返回null,请停下来想一想,这个地方是否更应该抛出一个异常 stackoverflow链接: -http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab=votes#tab-top +http://stackoverflow.com/questions/271526/avoiding-null-statements?page=1&tab=votes#tab-top From 77a1c0f90ca1f58dec253735f3503b6c1b836490 Mon Sep 17 00:00:00 2001 From: tuxiantian <791978859@qq.com> Date: Thu, 8 Jun 2017 16:31:37 +0800 Subject: [PATCH 084/108] Update iterate-through-a-hashmap.md --- contents/iterate-through-a-hashmap.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/iterate-through-a-hashmap.md b/contents/iterate-through-a-hashmap.md index 91807ac..24ac1ec 100644 --- a/contents/iterate-through-a-hashmap.md +++ b/contents/iterate-through-a-hashmap.md @@ -1,6 +1,6 @@ # HashMap遍历 # -在Java中有多种遍历HashMAp的方法。让我们回顾一下最常见的方法和它们各自的优缺点。由于所有的Map都实现了Map接口,所以接下来方法适用于所有Map(如:HaspMap,TreeMap,LinkedMap,HashTable,etc) +在Java中有多种遍历HashMap的方法。让我们回顾一下最常见的方法和它们各自的优缺点。由于所有的Map都实现了Map接口,所以接下来方法适用于所有Map(如:HaspMap,TreeMap,LinkedMap,HashTable,etc) ## 方法#1 使用For-Each迭代entries ## @@ -74,4 +74,4 @@ 如果你只需要使用key或者value使用方法#2,如果你坚持使用java的老版本(java 5 以前的版本)或者打算在迭代的时候移除entries,使用方法#3。其他情况请使用#1方法。避免使用#4方法。 stackoverflow链接: -http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap \ No newline at end of file +http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap From 124eadd509f55fa975b1a0f30ec9fb62edbe9ee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=A5=95=E6=85=A7?= Date: 2017年9月26日 00:31:18 +0800 Subject: [PATCH 085/108] =?UTF-8?q?look-enum-by-string-value.md=20?= =?UTF-8?q?=E6=8E=92=E7=89=88=E5=92=8C=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/lookup-enum-by-string-value.md | 31 ++++++++++++------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/contents/lookup-enum-by-string-value.md b/contents/lookup-enum-by-string-value.md index 160aafa..f1cb45a 100644 --- a/contents/lookup-enum-by-string-value.md +++ b/contents/lookup-enum-by-string-value.md @@ -1,18 +1,13 @@ -Java 中如何将 String 转换为 enum -======= +# Java 中如何将 String 转换为 enum -###问题 - -###我有一个 enum 类 - -``` java +### 问题 + enum 类 +```java public enum Blah { A, B, C, D } ``` -我想要找到一个 `String` 对应的 enum 值。例如, `"A"` 将是 `Blah.A`.如何做到? - -我需要使用 `Enum.valueOf()` 方法吗? 如果是该如何使用? +如何根据枚举类型的值(比如 "A" ) 得到 `Blah.A`? --- @@ -20,7 +15,8 @@ public enum Blah { 是的, `Blah.valueOf("A")` 将会给你 `Blah.A`. -静态方法 `valueof()` 和 `values()` 在编译时期被插入,并不存在于源码中。但是在Javadoc中;例如,[`Dialog.ModalityType`](http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html "Dialog.ModalityType")中显示了这两个方法。 +静态方法 `valueof()` 和 `values()` 在编译时期被插入,并不存在于源码中。 +但是在Javadoc中会显示;例如,[`Dialog.ModalityType`](http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html "Dialog.ModalityType")中显示了这两个方法。 ### A2 @@ -80,7 +76,7 @@ public static > T getEnumFromString(Class c, String string) return null; } ``` -之后,在我的enum类中通常如此使用来减少打字: +之后,在我的enum类中通常如此使用来减少代码量: ``` java public static MyEnum fromString(String name) { return getEnumFromString(MyEnum.class, name); @@ -91,8 +87,8 @@ public static MyEnum fromString(String name) { _评论区对于答主的异常处理一片指责 -译者注_ -###A4 -如果你不想编写自己的工具类,可以使用 Google的 `guava` 库: +### A4 +如果你不想编写自己的工具类,可以使用 Google的 [Google guava](https://github.com/google/guava) 库: ``` java Enums.getIfPresent(Blah.class, "A") ``` @@ -100,8 +96,11 @@ Enums.getIfPresent(Blah.class, "A") _完整方法签名 `Optional getIfPresent(Class enumClass, String value)` , `Optional` 对象可以优雅的解决null值问题 -译者注_ +> 注意: 返回的是 `Google Optional` 而不是 `Java Optional` + --- _其他的答案都大同小异,感兴趣的可以看原帖_ stackoverflow链接 -http://stackoverflow.com/questions/604424/lookup-enum-by-string-value -_译者:[MagicWolf](https://github.com/DaiDongLiang)_ +[Lookup enum by string value +](https://stackoverflow.com/questions/604424/lookup-enum-by-string-value) +_译者:[MagicWolf](https://github.com/DaiDongLiang)_ \ No newline at end of file From c24cd350cd9c5eecbf97ed07c8280aacd4be1743 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=A5=95=E6=85=A7?= Date: 2017年9月26日 00:39:24 +0800 Subject: [PATCH 086/108] update README --- README.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 624fcdb..6da8904 100644 --- a/README.md +++ b/README.md @@ -10,21 +10,22 @@ stackoverflow-Java-top-qa ------------- ### 如何参与翻译(欢迎加入翻译组QQ群485011036) -####如何参与: +#### 如何参与: - 请从下文"待翻译问题链接"中寻找你感兴趣的问答进行翻译。翻译好的问答,放到contents目录下,无需更新readme.md文档。之后提一个PR,我负责合并PR并更新到readme中。 - 另外,为了避免多人重复新翻译一个问题,你可以提issue,说明你计划翻译的问题及时间点,我可以先更新到下面的"未翻译问题"中,说明已有人领了这个问题。当然,也不一定要提issue,一般情况下,只要及时提pr,我及时审核,出现"撞车"的概率并不高。 -####一些基本的约定: +#### 一些基本的约定: - 文档的文件名,和stackoverflowhich-notnull-java-annotation-should-i-usew上的url保持一致。例如,http://stackoverflow.com/questions/8710619/java-operator 的文件名, 就是java-operator.md - 在每篇翻译文档内容的最后,要附上stackoverflow的原文链接 -####每个人可以做(但不限于): +#### 每个人可以做(但不限于): - 找未翻译的问题进行翻译 - 优化已翻译的问题 - 输出问答精简汇总版(把所有的问答集中到一个md文件,然后尽量精简,让别人可以在一天内把这100个问题的精髓都看完) - 输出gitbook版本(现在直接在github上查看,体验不好) -####文档优化反馈: +#### 文档优化反馈: + 请大家多多反馈,优化已翻译好的文章:可以到[吐槽区](https://github.com/giantray/stackoverflow-java-top-qa/issues/66)吐槽,也可以在已翻译文章基础上进行优化,提新的PR。文章质量的提升,需要大家一起努力! @@ -61,7 +62,6 @@ stackoverflow-Java-top-qa * [为什么Java的```Vector```类被认为是过时的或者废弃的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-java-vector-class-considered-obsolete-or-deprecated.md) * [Java的foreach循环是如何工作的](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-does-the-java-for-each-loop-work.md) * [为什么相减这两个时间(1927年)会得到奇怪的结果](/contents/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result.md) -* [Java 中如何将 String 转换为 enum](/contents/lookup-enum-by-string-value.md) * [该什么时候使用 ThreadLocal变量,它是如何工作的](/contents/when-and-how-should-i-use-a-threadlocal-variable.md) * [servlets的运行原理](/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md) * [如何计算MD5值](/contents/how-can-i-generate-an-md5-hash.md) @@ -122,7 +122,6 @@ stackoverflow-Java-top-qa ### 待翻译问题链接(还剩x问题) - [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) -- [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) - ['Must Override a Superclass Method' Errors after importing a project into Eclipse](http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) From d13b3b8f66b8b608f825a6a308c2f108cf889bf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=8B=E5=90=8D=E5=B1=B1=E8=BD=A6=E7=A5=9E?= Date: 2017年10月16日 21:41:10 -0500 Subject: [PATCH 087/108] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit markdown标准语法应该有个空格 --- contents/java-operator.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contents/java-operator.md b/contents/java-operator.md index cee3e03..ab967cc 100644 --- a/contents/java-operator.md +++ b/contents/java-operator.md @@ -1,6 +1,6 @@ -##Java += 操作符实质 +## Java += 操作符实质 -###问题 +### 问题 我之前以为: i += j 等同于 i = i + j; 但假设有: @@ -11,7 +11,7 @@ long j = 8; 这时 i = i + j 不能编译,但 i += j 却可以编译。这说明两者还是有差别的 这是否意味着,i += j,实际是等同于 i= (type of i) (i + j)呢? -###回答 +### 回答 这个问题,其实官方文档中已经解答了。 请看这里 [§15.26.2 Compound Assignment Operators](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2) From 8ddef1aca6269e818ebd50a4cc5b71d970efcae9 Mon Sep 17 00:00:00 2001 From: LI Daobing Date: Tue, 3 Jul 2018 13:21:25 +0800 Subject: [PATCH 088/108] Update how-to-sort-a-mapkey-value-on-the-values-in-java.md --- .../how-to-sort-a-mapkey-value-on-the-values-in-java.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md b/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md index b9fecfb..31b36ec 100644 --- a/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md +++ b/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md @@ -1,6 +1,6 @@ -##`Map`基于Value值排序 +## `Map`基于Value值排序 -###方法1: +### 方法1: 使用TreeMap,可以参考下面的代码 ```java public class Testing { @@ -43,7 +43,7 @@ class ValueComparator implements Comparator { ``` 译注:如果不自己写Comparator,treemap默认是用key来排序 -###方法2: +### 方法2: 先通过linkedlist排好序,再放到LinkedHashMap中 ```java @@ -74,4 +74,4 @@ public class MapUtil 译注:这两种方法,我简单测试了下,如果map的size在十万级别以上,两者的耗时都是几百毫秒,第二个方法会快一些。否则,第一个方法快一些。因此,如果你处理的map,都是几十万级别以下的大小,两种方式随意使用,看个人喜欢了。 stackoverflow链接: -http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java \ No newline at end of file +http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java From 79c54d97926ac510a3213b14735ad3cada20f94b Mon Sep 17 00:00:00 2001 From: LI Daobing Date: Tue, 3 Jul 2018 13:23:05 +0800 Subject: [PATCH 089/108] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 624fcdb..3bdf099 100644 --- a/README.md +++ b/README.md @@ -10,21 +10,21 @@ stackoverflow-Java-top-qa ------------- ### 如何参与翻译(欢迎加入翻译组QQ群485011036) -####如何参与: +#### 如何参与: - 请从下文"待翻译问题链接"中寻找你感兴趣的问答进行翻译。翻译好的问答,放到contents目录下,无需更新readme.md文档。之后提一个PR,我负责合并PR并更新到readme中。 - 另外,为了避免多人重复新翻译一个问题,你可以提issue,说明你计划翻译的问题及时间点,我可以先更新到下面的"未翻译问题"中,说明已有人领了这个问题。当然,也不一定要提issue,一般情况下,只要及时提pr,我及时审核,出现"撞车"的概率并不高。 -####一些基本的约定: +#### 一些基本的约定: - 文档的文件名,和stackoverflowhich-notnull-java-annotation-should-i-usew上的url保持一致。例如,http://stackoverflow.com/questions/8710619/java-operator 的文件名, 就是java-operator.md - 在每篇翻译文档内容的最后,要附上stackoverflow的原文链接 -####每个人可以做(但不限于): +#### 每个人可以做(但不限于): - 找未翻译的问题进行翻译 - 优化已翻译的问题 - 输出问答精简汇总版(把所有的问答集中到一个md文件,然后尽量精简,让别人可以在一天内把这100个问题的精髓都看完) - 输出gitbook版本(现在直接在github上查看,体验不好) -####文档优化反馈: +#### 文档优化反馈: 请大家多多反馈,优化已翻译好的文章:可以到[吐槽区](https://github.com/giantray/stackoverflow-java-top-qa/issues/66)吐槽,也可以在已翻译文章基础上进行优化,提新的PR。文章质量的提升,需要大家一起努力! From 74b36bb1486b39baaf094dd5768fbc170d9e5b24 Mon Sep 17 00:00:00 2001 From: razyer <623065552@qq.com> Date: 2018年8月15日 21:03:09 +0800 Subject: [PATCH 090/108] =?UTF-8?q?=E8=B0=83=E6=95=B4markdown=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=EF=BC=8C=E6=8F=90=E9=AB=98=E6=98=BE=E7=A4=BA=E5=92=8C?= =?UTF-8?q?=E9=98=85=E8=AF=BB=E6=95=88=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ation-shared-variables-and-multithreading.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md b/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md index 148ab53..4539697 100644 --- a/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md +++ b/contents/how-do-servlets-work-instantiation-shared-variables-and-multithreading.md @@ -1,13 +1,14 @@ -##How do servlets work? Instantiation, shared variables and multithreading -###问题: +## How do servlets work? Instantiation, shared variables and multithreading +### 问题: 假设,我有一个web服务器可以支持无数的servlets,对于通过这些servlets的信息,我正在获取这些servlets的上下文环境,并设置session变量。 现在,如果有两个或者更多的user用户发送请求到这个服务器,session变量会发生什么变化?session对于所有的user是公共的还是不同的user拥有不同的session。如果用户彼此之间的session是不同的,那么服务器怎么区分辨别不同的用户呢? 另外一些相似的问题,如果有N个用户访问一个具体的servlets,那么这个servlets是只在第一个用户第一次访问的时候实例化,还是为每一个用户各自实例化呢? -###答案: -####ServletContext + +### 答案: +#### ServletContext 当servletcontainer(像tomcat)启动的时候,它会部署和加载所有的webapplications,当一个webapplication加载完成后,servletcontainer就会创建一个ServletContext,并且保存在服务器的内存中。这个webapp的web.xml会被解析,web.xml中的每个```, and ```或者通过注解```@WebServlet, @WebFilter and @WebListener```,都会被创建一次并且也保存在服务器的内存中。对于所有filter,```init()```方法会被直接触发,当servletcontainer关闭的时候,它会unload所有的webapplications,触发所有实例化的servlets和filters的```destroy()```方法,最后,servletcontext和所有的servlets,filter和listener实例都会被销毁。 -####HttpServletRequest and HttpServletResponse +#### HttpServletRequest and HttpServletResponse servletcontainer 是附属于webserver的,而这个webserver会持续监听一个目标端口的```HTTP request```请求,这个端口在开发中经常会被设置成8080,而在生产环境会被设置成80。当一个客户端(比如用户的浏览器)发送一个HTTP request,servletcontainer就会创建新的HttpServletRequest对象和HttpServletResponse对象。。。。 在有filter的情况下,```doFilter()```方法会被触发。当代码调用```chain.doFilter(request, response)```时候,请求会经过下一个过滤器filter,如果没有了过滤器,会到达servlet。在servlets的情况下,```service()```触发,然后根据```request.getMethod()```确定执行doGet()还是```doPost()```,如果当前servlet找不到请求的方法,返回405error。 @@ -22,14 +23,14 @@ request对象提供了HTTP请求所有的信息,比如request headers和reques 只要没超过``````设定的值,httpSession对象会一直存在,``````大小可以在web.xml中设定,默认是30分钟。所以如果连续30分钟之内客户端不再访问webapp,servletcontainer就会销毁对应的session。接下来的request请求即使cookies依旧存在,但是却不再有对应的session了。servletcontainer 会创建新的session。 另外一方面,session cookie在浏览器端有默认的生命时长,就是只要浏览器一直在运行,所以当浏览器关闭,浏览器端的cookie会被销毁。 -####最后 +#### 总结 - 只要webapp存在,ServletContext 一定会存在。并且ServletContext 是被所有session和request共享的。 - 只要客户端用同一个浏览器和webapp交互并且该session没有在服务端超时,HttpSession 就会一直存在。并且在同一个会话中所有请求都是共享的。 - 只有当完整的response响应到达,HttpServletRequest 和 HttpServletResponse才不再存活,并且不被共享。 - 只要webapp存在,servlet、filter和listener就会存在。他们被所有请求和会话共享。 - 只要问题中的对象存在,任何设置在ServletContext, HttpServletRequest 和 HttpSession中的属性就会存在。 -####线程安全 +#### 线程安全 就是说,你主要关注的是线程安全性。你应该了解到,servlets和filter是被所有请求共享的。这正是Java的美妙之处,它的多线程和不同的线程可以充分利用同样的实例instance,否则对于每一个request请求都要重复创建和调用init()和destroy()开销太大。 但是你也应该注意到,你不应该把任何请求或会话作用域的数据作为一个servlet或过滤器的实例变量。这样会被其他会话的请求共享,并且那是线程不安全的!下面的例子阐明的这点: @@ -49,4 +50,4 @@ public class ExampleServlet extends HttpServlet { stackoverflow链接: -http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-shared-variables-and-multithreading \ No newline at end of file +http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-shared-variables-and-multithreading From 6e490df68e6dc374767a8a4e5cdfdaed8537e8c9 Mon Sep 17 00:00:00 2001 From: jayknoxqu Date: 2018年10月17日 22:13:00 +0800 Subject: [PATCH 091/108] Update how-can-i-initialize-a-static-map.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正文中错误代码! --- contents/how-can-i-initialize-a-static-map.md | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/contents/how-can-i-initialize-a-static-map.md b/contents/how-can-i-initialize-a-static-map.md index 71b83a5..a85057f 100644 --- a/contents/how-can-i-initialize-a-static-map.md +++ b/contents/how-can-i-initialize-a-static-map.md @@ -52,23 +52,23 @@ 我喜欢用Guava(是 Collection 框架的增强)的方法初始化一个静态的,不可改变的map - static fianl Map myMap = ImmutablMap.of( - 1,"one", - 2, "two" - ) + static final Map MY_MAP = ImmutableMap.of( + 1, "one", + 2, "two" + ); + · 当map的 entry个数超过5个时,你就不能使用`ImmutableMap.of`。可以试试`ImmutableMap.bulider()` - static fianl Map myMap = ImmutableMap.builder() - { - .put(1, "one") - .put(2, "two") - - .put(15, "fifteen") - .build(); - } + static final Map MY_MAP = ImmutableMap.builder() + .put(1, "one") + .put(2, "two") + // ... + .put(15, "fifteen") + .build(); + # 原文链接 # -http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map \ No newline at end of file +http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map From 5eee13fde9ecc97c227a4c3f060165ac10c87f94 Mon Sep 17 00:00:00 2001 From: indicolite Date: 2018年10月26日 14:44:29 +0800 Subject: [PATCH 092/108] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 624fcdb..3bdf099 100644 --- a/README.md +++ b/README.md @@ -10,21 +10,21 @@ stackoverflow-Java-top-qa ------------- ### 如何参与翻译(欢迎加入翻译组QQ群485011036) -####如何参与: +#### 如何参与: - 请从下文"待翻译问题链接"中寻找你感兴趣的问答进行翻译。翻译好的问答,放到contents目录下,无需更新readme.md文档。之后提一个PR,我负责合并PR并更新到readme中。 - 另外,为了避免多人重复新翻译一个问题,你可以提issue,说明你计划翻译的问题及时间点,我可以先更新到下面的"未翻译问题"中,说明已有人领了这个问题。当然,也不一定要提issue,一般情况下,只要及时提pr,我及时审核,出现"撞车"的概率并不高。 -####一些基本的约定: +#### 一些基本的约定: - 文档的文件名,和stackoverflowhich-notnull-java-annotation-should-i-usew上的url保持一致。例如,http://stackoverflow.com/questions/8710619/java-operator 的文件名, 就是java-operator.md - 在每篇翻译文档内容的最后,要附上stackoverflow的原文链接 -####每个人可以做(但不限于): +#### 每个人可以做(但不限于): - 找未翻译的问题进行翻译 - 优化已翻译的问题 - 输出问答精简汇总版(把所有的问答集中到一个md文件,然后尽量精简,让别人可以在一天内把这100个问题的精髓都看完) - 输出gitbook版本(现在直接在github上查看,体验不好) -####文档优化反馈: +#### 文档优化反馈: 请大家多多反馈,优化已翻译好的文章:可以到[吐槽区](https://github.com/giantray/stackoverflow-java-top-qa/issues/66)吐槽,也可以在已翻译文章基础上进行优化,提新的PR。文章质量的提升,需要大家一起努力! From b7d20aad25e82a1dbbfc479e643a03540007cf37 Mon Sep 17 00:00:00 2001 From: 245455758 <30688227+245455758@users.noreply.github.com> Date: 2018年10月28日 21:26:45 +0800 Subject: [PATCH 093/108] Create how-to-get-an-enum-value-from-a-string-value-in-java.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 创建文件 --- contents/how-to-get-an-enum-value-from-a-string-value-in-java.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 contents/how-to-get-an-enum-value-from-a-string-value-in-java.md diff --git a/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md b/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md @@ -0,0 +1 @@ + From cf30c73f9e87a9398cbc850adee21a10e8d96520 Mon Sep 17 00:00:00 2001 From: 245455758 <30688227+245455758@users.noreply.github.com> Date: 2018年10月28日 22:32:14 +0800 Subject: [PATCH 094/108] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E4=BA=86=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-enum-value-from-a-string-value-in-java.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md b/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md index 8b13789..66d634b 100644 --- a/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md +++ b/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md @@ -1 +1,25 @@ +## 标题 +### 问题: + 假如说我有一个如下的枚举类 + +```java + public enum Blah { + A, B, C, D + } +``` +而我想要找出具有指定名称的枚举类型对应的的字符串类型的枚举常量,打个比方``"A"``对应的值为``Blah.A``。 +此时我应该怎么做? +我是不是应该使用``Enum.valueOf()``这个方法?如果是的话,我又该怎么使用它? + +### 回答: +是的,``Blah.valueOf("A")``将会给你你想要的``Blah.A`` +不过需要注意的是,你输入的名字必须是绝对匹配的,像``Blah.valueOf("a")``和``Blah.valueOf("A ")``都会抛出``IllegalArgumentException`` +注:第一个表达式``a`` 与``A``不匹配 +第二个表达式``A ``后面多了一个空格 + +静态方法``valueOf()``和``values()``在编译时创建并且不会出现在编译后的源码里。但尽管如此,这两个方法还是确实出现在了Java文档里,[文档连接](https://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html) + +stackoverflow讨论地址 [https://stackoverflow.com/questions/604424/how-to-get-an-enum-value-from-a-string-value-in-java](https://stackoverflow.com/questions/604424/how-to-get-an-enum-value-from-a-string-value-in-java) + + From f01f9808a7d13e4e194be4c317b724d96aca7fa3 Mon Sep 17 00:00:00 2001 From: 245455758 <30688227+245455758@users.noreply.github.com> Date: 2018年10月28日 22:39:53 +0800 Subject: [PATCH 095/108] Update how-to-get-an-enum-value-from-a-string-value-in-java.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 完善页面 --- .../how-to-get-an-enum-value-from-a-string-value-in-java.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md b/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md index 66d634b..b8a0a12 100644 --- a/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md +++ b/contents/how-to-get-an-enum-value-from-a-string-value-in-java.md @@ -1,7 +1,7 @@ -## 标题 +## 怎样得到指定名称的枚举类型对应的的字符串类型的枚举常量 ### 问题: - 假如说我有一个如下的枚举类 +假如说我有一个如下的枚举类 ```java public enum Blah { @@ -13,7 +13,7 @@ 我是不是应该使用``Enum.valueOf()``这个方法?如果是的话,我又该怎么使用它? ### 回答: -是的,``Blah.valueOf("A")``将会给你你想要的``Blah.A`` +是的,``Blah.valueOf("A")``将会给你你想要的``Blah.A`` 不过需要注意的是,你输入的名字必须是绝对匹配的,像``Blah.valueOf("a")``和``Blah.valueOf("A ")``都会抛出``IllegalArgumentException`` 注:第一个表达式``a`` 与``A``不匹配 第二个表达式``A ``后面多了一个空格 From ca2b24df27edcc6d236dda52acdbb6b77ff9022c Mon Sep 17 00:00:00 2001 From: 245455758 <30688227+245455758@users.noreply.github.com> Date: 2018年10月29日 11:28:52 +0800 Subject: [PATCH 096/108] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/why-does-this-go-into-an-infinite-loop | 1 + 1 file changed, 1 insertion(+) create mode 100644 contents/why-does-this-go-into-an-infinite-loop diff --git a/contents/why-does-this-go-into-an-infinite-loop b/contents/why-does-this-go-into-an-infinite-loop new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/contents/why-does-this-go-into-an-infinite-loop @@ -0,0 +1 @@ + From 7500914ef82d80e07c0c6a9c07212e67e3bee87b Mon Sep 17 00:00:00 2001 From: 245455758 <30688227+245455758@users.noreply.github.com> Date: 2018年10月29日 11:31:45 +0800 Subject: [PATCH 097/108] =?UTF-8?q?=E5=AE=8C=E6=88=90=E6=A0=87=E9=A2=98?= =?UTF-8?q?=E7=A1=AE=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/why-does-this-go-into-an-infinite-loop | 1 + 1 file changed, 1 insertion(+) diff --git a/contents/why-does-this-go-into-an-infinite-loop b/contents/why-does-this-go-into-an-infinite-loop index 8b13789..33787a9 100644 --- a/contents/why-does-this-go-into-an-infinite-loop +++ b/contents/why-does-this-go-into-an-infinite-loop @@ -1 +1,2 @@ +## 为什么它会进入死循环 From 6850f0cc36a8a7b34afbfd73856a2b09e8c9e3a2 Mon Sep 17 00:00:00 2001 From: withlimin <42736147+withlimin@users.noreply.github.com> Date: 2019年4月11日 11:46:08 +0800 Subject: [PATCH 098/108] Create how-do-i-decompile-java-class-files.md https://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files --- .../how-do-i-decompile-java-class-files.md | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 contents/how-do-i-decompile-java-class-files.md diff --git a/contents/how-do-i-decompile-java-class-files.md b/contents/how-do-i-decompile-java-class-files.md new file mode 100644 index 0000000..8a28fc2 --- /dev/null +++ b/contents/how-do-i-decompile-java-class-files.md @@ -0,0 +1,65 @@ +## 如何对Java class文件进行反编译 ## + +可以用什么程序来编译class文件 会得到java代码还是JVM编译的代码? +在这个网站上性能讨论的问题上经常看到进行反编译文件来看编译器如何优化一些东西 + +"反编译"的艺术也可以被认为是逆向工程。虽然有时在逆向工程时你并不总是能够访问二进制文件。 + + +没人提到 bytecodeviewer.com吗,它可以反编译为java源码和字节码(对于java源码是基于JAD) + +**www.javadecompilers.com** + + 它是最流行的Java编译器,用c++编写,速度很快 + 比较过时,且不提供支持,不支持Java5及以后的版本 +这个网站也列出了其他的工具。 + +正如Salvador Valencia在评论(2017年9月)中所说 javadecompiler提供了一个SaaS,您可以将.cl​​ass文件上传到云端,并返回反编译代码。 +(原答案:2008年10月) +定义J2SE 5.0(Java SE 5)主要功能的JSR 176的最终版本已于2004年9月30日发布。 +由Pavel Kouznetsov先生编写的着名Java反编译器JAD支持的最新Java版本是JDK 1.3。 + + +Java Decompiler(一个快速Java反编译器)具有: +显式支持反编译和分析Java 5+".class"文件。 +一个很好的GUI: +![](https://i.imgur.com/iXIWcl8.png) + +它适用于从JDK 1.1.8到JDK 1.7.0以及其他(Jikes,JRockit等)的编译器。 +它具有在线实时演示版本,实际上功能齐全!你可以在页面上删除一个jar文件,看看反编译的源代码而不安装任何东西。 + + +比如: +Procyon:开源(Apache 2) +Krakatau:开源(GPLv3) +CFR:开源(MIT) +JAD +DJ Java Decompiler +Mocha +还有很多。 + +这些产生Java代码,可以让你看到JVM字节码。 +要查看Java源代码,请检查一些反编译器。去搜索jad。 +如果要查看字节码,只需使用JDK附带的javap即可。 + + + +我试了几个,Procyon对我来是最好的。它正在积极开发中,并支持最新版Java的许多功能。 + +以下是我试过的其他的: +CFR +还可以,但是经常反编译失败。我会密切注意这个。还积极开发支持最新的Java功能。 +Krakatau +采用不同的方法,它尝试输出等效的Java代码,而不是尝试重建原始源,这有可能使混淆代码更好。根据我的测试,它与Procyon大致相当,但仍然很高兴有不同的东西。我确实必须使用-skip命令行标志,因此它不会停止错误。积极开发,有趣的是它是用Python编写的。 +JD-GUI +工作,但Procyon的输出要好得多。这是一个将Procyon输出与原始和JD-GUI进行比较的页面。 JD-GUI也可以作为Eclipse插件使用,它根本不适用于我。似乎不是开源的,发展似乎是零星的。 +JAD +工作,但只支持Java 1.4及更低版本。也可以作为Eclipse插件使用。不再在开发中。 + + +我使用JAD Decompiler。 +有一个Eclipse插件,jadeclipse。这挺好用的。 + + +JD-GUI真的很棒。你可以打开一个jar文件并浏览代码,就好像正在使用IDE一样。好东西。 + From a2fe2a2463a868b961c42b45ec937b3e65b4dbcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E9=80=9F=E8=9C=97=E7=89=9B?= <31986081+jisu-woniu@users.noreply.github.com> Date: 2019年4月20日 18:49:48 -0500 Subject: [PATCH 099/108] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/read-convert-an-inputstream-to-a-string.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contents/read-convert-an-inputstream-to-a-string.md b/contents/read-convert-an-inputstream-to-a-string.md index 55aefec..8807e6f 100644 --- a/contents/read-convert-an-inputstream-to-a-string.md +++ b/contents/read-convert-an-inputstream-to-a-string.md @@ -9,8 +9,9 @@ IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString(); ``` 或者 +```java String theString = IOUtils.toString(inputStream, encoding)//这个方法其实封装了上面的方法,减少了一个参数 - +``` ###使用原生库 如果不想引入Apache库,也可以这样做 ```java From 451cea2dfee4e5a0f0e41fae0a85b94756c2be72 Mon Sep 17 00:00:00 2001 From: zsgwsjj <749940957@qq.com> Date: 2019年5月14日 10:37:52 +0800 Subject: [PATCH 100/108] Update java-operator.md --- contents/java-operator.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contents/java-operator.md b/contents/java-operator.md index cee3e03..ab967cc 100644 --- a/contents/java-operator.md +++ b/contents/java-operator.md @@ -1,6 +1,6 @@ -##Java += 操作符实质 +## Java += 操作符实质 -###问题 +### 问题 我之前以为: i += j 等同于 i = i + j; 但假设有: @@ -11,7 +11,7 @@ long j = 8; 这时 i = i + j 不能编译,但 i += j 却可以编译。这说明两者还是有差别的 这是否意味着,i += j,实际是等同于 i= (type of i) (i + j)呢? -###回答 +### 回答 这个问题,其实官方文档中已经解答了。 请看这里 [§15.26.2 Compound Assignment Operators](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2) From 84c06679902c840e9c596dfb78e8c7e0e698c04a Mon Sep 17 00:00:00 2001 From: Jarbitz Date: 2019年5月21日 17:29:36 +0800 Subject: [PATCH 101/108] Update how-to-sort-a-mapkey-value-on-the-values-in-java.md title # mark --- .../how-to-sort-a-mapkey-value-on-the-values-in-java.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md b/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md index b9fecfb..31b36ec 100644 --- a/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md +++ b/contents/how-to-sort-a-mapkey-value-on-the-values-in-java.md @@ -1,6 +1,6 @@ -##`Map`基于Value值排序 +## `Map`基于Value值排序 -###方法1: +### 方法1: 使用TreeMap,可以参考下面的代码 ```java public class Testing { @@ -43,7 +43,7 @@ class ValueComparator implements Comparator { ``` 译注:如果不自己写Comparator,treemap默认是用key来排序 -###方法2: +### 方法2: 先通过linkedlist排好序,再放到LinkedHashMap中 ```java @@ -74,4 +74,4 @@ public class MapUtil 译注:这两种方法,我简单测试了下,如果map的size在十万级别以上,两者的耗时都是几百毫秒,第二个方法会快一些。否则,第一个方法快一些。因此,如果你处理的map,都是几十万级别以下的大小,两种方式随意使用,看个人喜欢了。 stackoverflow链接: -http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java \ No newline at end of file +http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java From b6ef88397d1cd2bb6317fa5b74f551feb14e271f Mon Sep 17 00:00:00 2001 From: seuwh2018 Date: 2019年5月27日 15:57:52 +0800 Subject: [PATCH 102/108] translation the question Why does this go into an infinite loop? --- contents/what-the-equivalent-of-x=x++.md | 106 +++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 contents/what-the-equivalent-of-x=x++.md diff --git a/contents/what-the-equivalent-of-x=x++.md b/contents/what-the-equivalent-of-x=x++.md new file mode 100644 index 0000000..1857b40 --- /dev/null +++ b/contents/what-the-equivalent-of-x=x++.md @@ -0,0 +1,106 @@ +## x=x++最终x等于多少? +### 问题描述: +``` +public class Tests { + public static void main(String[] args) throws Exception { + int x = 0; + while(x<3) { + x = x++; + System.out.println(x); + } + } +} +``` +如上,程序会进入死循环,我们知道通常对于x自增是通过x++或者x=x+1,那么为什么x=x++不是对x自增再赋值给x? + +### 回答: +明确x=x++处理流程,相当于: +```java +int temp=x; +x++; +x=temp; +``` +#### 解释: +考虑如下类: +```java +class test { + public static void main(String[] args) { + int i=0; + i=i++; + } +} +``` +通过运行反汇编: +```bash +$ javap -c test +``` +可以得到: +```java +Compiled from "test.java" +class test extends java.lang.Object{ +test(); + Code: + 0: aload_0 + 1: invokespecial #1; //Method java/lang/Object."":()V + 4: return + +public static void main(java.lang.String[]); + Code: + 0: iconst_0 + 1: istore_1 + 2: iload_1 + 3: iinc 1, 1 + 6: istore_1 + 7: return +} +``` +以下来解释其中的助记符: +* iconst_0: 常量0被push入栈。 + +* istore_1: 栈顶元素被pop出,然后存储在索引为1的局部变量也就是x内。 + +* iload_1 : 索引为1的局部变量(即x)的值被push入栈,此时栈顶值为0。 + +* iinc 1, 1 :索引为1的量增加为1,也就是x变为1。 + +* istore_1 : 栈顶值被pop出,存入索引为1的局部变量中,因此x再次变为0。 + +以上,可以知道x=x++由于入栈出栈,x的值并未变化。 + +#### 对比:x=++x +```java +class test { + public static void main(String[] args) { + int i=0; + i=++i; + } +} +``` +运行 +```bash +$ javac test.java +$ javap -c test +``` +得到: +```java +Compiled from "test.java" +class test { + test(); + Code: + 0: aload_0 + 1: invokespecial #1 // Method java/lang/Object."":()V + 4: return + + public static void main(java.lang.String[]); + Code: + 0: iconst_0 + 1: istore_1 + 2: iinc 1, 1 + 5: iload_1 + 6: istore_1 + 7: return +} +``` +可以看出是先对x进行加一,再将x的值push入栈,随后再将栈顶值赋给x。 + + From 739fe6dee9f407c0639e665a473f95a28f0ab8c4 Mon Sep 17 00:00:00 2001 From: lizeyang Date: 2019年9月14日 15:25:02 +0800 Subject: [PATCH 103/108] Merge branch 'smj' of https://github.com/AutumnLight/stackoverflow-java-top-qa into AutumnLight-smj # Conflicts: # contents/how-can-i-generate-an-md5-hash.md # contents/why-is-printing-b-dramatically-slower-than-printing.md --- ...setting-multiple-jars-in-java-classpath.md | 38 ++++ ...ing-b-dramatically-slower-than-printing.md | 165 ++++++------------ 2 files changed, 94 insertions(+), 109 deletions(-) create mode 100644 contents/setting-multiple-jars-in-java-classpath.md diff --git a/contents/setting-multiple-jars-in-java-classpath.md b/contents/setting-multiple-jars-in-java-classpath.md new file mode 100644 index 0000000..6549e70 --- /dev/null +++ b/contents/setting-multiple-jars-in-java-classpath.md @@ -0,0 +1,38 @@ +##如何在classpath中设置多个jar包? + +###问题 +是否有一个方法可以在classpath选项中包含一个文件夹(目录)下的所有jar包? +我尝试运行`java -classpath lib/*.jar:. my.package.Program`,但是无法找到相应的类文件,可是这些类文件确实存在于命令中的jar包中。我是否需要在classpath中分别指定所有的jar包? + +###回答 +在使用Java6或者以上版本时,classpath选项可以支持通配符(wildcards)。使用方法如下: +* 使用直接引用(`"`) +* 使用 `*` 而不是 `*.jar` + +**Windows平台** + +`java -cp "Test.jar;lib/*" my.package.MainClass` + +**Unix平台** + +`java -cp "Test.jar:lib/*" my.package.MainClass` + +Unix平台与Windows平台基本一样,除了使用冒号 `:` 替代分号 `;` 之外。如果你不能使用通配符,也可以使用`bash`完成上述功能,命令如下(其中lib是一个包含所有jar包的目录): +`java -cp $(echo lib/*.jar | tr ' ' ':')` + +注意事项:classpath选项与-jar选项并不能兼容。可以查看:[Execute jar file with multiple classpath libraries from command prompt](http://stackoverflow.com/questions/13018100/execute-jar-file-with-multiple-classpath-libraries-from-command-prompt) + +**对于通配符的理解** +来自[Classpath](http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html)文档: + +类路径可以包含一个基本文件名通配符`*`,其等价于指定一个特定目录下的所有以.jar或.JAR为后缀的文件的列表。例如,一个类路径的条目为`foo/*`,其指定了foo目录下的所有jar文件。一个仅仅包含`*`的classpath条目(entry)指定了当前目录下的所有jar包。 + +一个包含了`*`的classpath条目不能匹配特定目录下的class文件。为了既能匹配foo目录下的类文件,也能匹配jar包,可以使用`foo;foo/*`或`foo/*;foo`。对于前者而言,类文件和资源选择的顺序先是foo目录下的类文件和资源,之后才是jar包;而后者则正好相反。 + +通配符并不能递归地搜索子目录下的jar包。例如,`foo/*`只找`foo`目录下的jar包,而不会寻找`foo/bar`,`foo/baz`等目录下的jar包。 + +一个目录中的jar包枚举顺序并不固定,这不仅和平台有关,甚至可能会在同一个机器上因为时间不同而表现不同。一个结构良好(well-constructed)的应用不应该依赖于某个特定的顺序。如果特定顺序是不可避免的时候,就需要在classpath中显示枚举所有的jar包了。 + +在类加载进程中,通配符的扩展在早期完成,优先于程序main函数的调用,而不是在其后。每个包含通配符的类路径都被替换为所在目录下所有jar包的序列。例如,如果目录`foo`包含`a.jar`,`b.jar`以及`c.jar`,因此类路径`foo/*`被扩展为`foo/a.jar;foo/b.jar;foo/c.jar`,并且以上字符串被作为系统属性`java.class.path`的值。 + +环境变量`CLASSPATH`与命令行选项-classpath或者-cp并没有什么不同。也就是说,通配符既可以应用于命令行`-classpath/-cp`选项中,也可以应用于环境变量`CLASSPATH`中。 \ No newline at end of file diff --git a/contents/why-is-printing-b-dramatically-slower-than-printing.md b/contents/why-is-printing-b-dramatically-slower-than-printing.md index 970dbde..4887753 100644 --- a/contents/why-is-printing-b-dramatically-slower-than-printing.md +++ b/contents/why-is-printing-b-dramatically-slower-than-printing.md @@ -1,114 +1,61 @@ -# 为什么打印"B"会明显的比打印"#"慢 - -## 问题 - -我生成了两个`1000`x`1000`的矩阵: - -第一个矩阵:`O`和`#`。 -第二个矩阵:`O`和`B`。 - -使用如下的代码,生成第一个矩阵需要8.52秒: - - Random r = new Random(); - for (int i = 0; i < 1000; i++) { - for (int j = 0; j < 1000; j++) { - if(r.nextInt(4) == 0) { - System.out.print("O"); - } else { - System.out.print("#"); - } - } - - System.out.println(""); - } - - -而使用这段代码,生成第二个矩阵花费了259.152秒: - - Random r = new Random(); - for (int i = 0; i < 1000; i++) { - for (int j = 0; j < 1000; j++) { - if(r.nextInt(4) == 0) { - System.out.print("O"); - } else { - System.out.print("B"); //only line changed - } +##为什么打印B要比打印#慢很多? + +###问题 +我生成了两个大小为 1000 * 1000 的矩阵 +第一个矩阵:O和# +第二个矩阵:O和B +使用以下代码,第一个矩阵仅用时8.25s就完成了: +```java +Random r = new Random(); +for (int i = 0; i < 1000; i++) { + for (int j = 0; j < 1000; j++) { + if(r.nextInt(4) == 0) { + System.out.print("O"); + } else { + System.out.print("#"); } - - System.out.println(""); } -如此大的运行时间差异的背后究竟是什么原因呢? - ---- - -正如评论中所建议的,只打印`System.out.print("#");`用时7.8871秒,而`System.out.print("B");`则给出`still printing...`。 - -另外有人指出这段代码对他们来说是正常的, 我使用了[Ideone.com](http://ideone.com),这两段代码的执行速度是相同的。 - -测试条件: - - - 我在Netbeans 7.2中运行测试,由控制台显示输出 - - 我使用了`System.nanoTime()`来计算时间 - -## 解答一 - -*纯粹的推测*是因为你使用的终端尝试使用[单词换行][1]而不是字符换行,并且它认为`B`是一个单词而`#`却不是。所以当它到达行尾并且寻找一个换行的地方的时候,如果是`#`就可以马上换行;而如果是`B`,它则需要花更长时间搜索,因为可能会有更多的内容才能换行(在某些终端会非常费时,比如说它会先输出退格再输出空格去覆盖被换行的那部分字符)。 - -但这都只是纯粹的推测。 - - - [1]: http://en.wikipedia.org/wiki/Word_wrap - - -##解答二 - -我用Eclipse和Netbeans 8.0.2做了测试,他们的Java版本都是1.8;我用了`System.nanoTime()`来计时。 - -##Eclipse: - -我得到了**用时相同的结果** - 大约**1.564秒**。 - -##Netbeans: - -* 使用"#": **1.536秒** -* 使用"B": **44.164秒** - -所以看起来像是Netbeans输出到控制台的性能问题。 - -在做了更多研究以后我发现问题所在是Netbeans [换行][1] 的最大缓存(这并不限于`System.out.println`命令),参见以下代码: - - for (int i = 0; i < 1000; i++) { - long t1 = System.nanoTime(); - System.out.print("BBB......BBB"); \\<-contain 1000 "B" - long t2 = System.nanoTime(); - System.out.println(t2-t1); - System.out.println(""); + System.out.println(""); + } +```` +而使用相同的代码时,第二个矩阵却执行了259.152s +````java +Random r = new Random(); +for (int i = 0; i < 1000; i++) { + for (int j = 0; j < 1000; j++) { + if(r.nextInt(4) == 0) { + System.out.print("O"); + } else { + System.out.print("B"); + } } -每一个循环所花费的时间都不到1毫秒,除了 **每第五个循环**会花掉大约225毫秒。像这样(单位是毫秒): - - BBB...31744 - BBB...31744 - BBB...31744 - BBB...31744 - BBB...226365807 - BBB...31744 - BBB...31744 - BBB...31744 - BBB...31744 - BBB...226365807 - . - . - . - -以此类推。 - -##总结: - -1. 使用Eclipse打印"B"完全没有问题 -1. Netbeans有换行的问题但是可以被解决(因为在Eclipse并没有这个问题)(而不用在B后面添加空格("B "))。 - - [1]: http://en.wikipedia.org/wiki/Line_wrap_and_word_wrap - -stackoverflow原址:http://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing + System.out.println(""); + } +```` +为什么两者的执行时间会有如此巨大的差距? +- - - +评论中一些人建议仅执行`System.out.print("#");`以及`System.out.print("B");`前者用时7.8871s,而后者仍然在打印(即花费时间过多--译者注) +另外有些人指出在他们那里工作正常(即两者花费时间差不错--译者注),我在[Ideone.com](http://ideone.com/)环境中运行两段代码,执行时间也差不多。 + +测试条件: +- Netbeans 7.2,结果输出在IDE的控制台 +- 使用`System.nanoTime()`度量时间 + +###回答 +纯推测:你正在使用的终端试图进行["自动换行"(word-wrapping)](http://en.wikipedia.org/wiki/Word_wrap),而不是"字符换行"(character-wrapping),并且将'B'视为一个单词字符(word character),而'#'视为一个非单词字符(non-word character)。因此当输出到达行尾时,控制台搜索一个位置用来换行,当遇到'#'时可以立即执行换行;然而遇到'B'时,控制台必须继续搜索,并且可能有更多的字符需要换行(这个操作在一些控制台上可能花销很大,例如,输出退格,然后输出空白字符来覆盖那些需要被换行的字符)。 +但是,这仅仅是理论推测。 + +**译者注:** +对于"word-wrapping"和"character-wrapping",我的理解是,它们的区别在于换行时是否在一个单词内部分割,例如在 charac-ter 中的-处换行,"word-wrapping"会将character全部移到下一行,而"character-wrapping"则将ter移到下一行,而charac依旧在原来的位置。 +**word-wrapping** +``` +******* +character +``` +**character-wrapping** +``` +*******charac +ter +``` \ No newline at end of file From 13a99f77dfb412b12456a7a0e6a18eb5fa040661 Mon Sep 17 00:00:00 2001 From: lizeyang Date: 2019年9月14日 15:30:59 +0800 Subject: [PATCH 104/108] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=93=BE=E6=8E=A5?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E3=80=82close=20#97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a21ea81..4580d52 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ stackoverflow-Java-top-qa * [如何在整数左填充0](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) * [在调用 instanceof 前需要进行null检查吗](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-null-check-needed-before-calling-instanceof.md) * [如何从文件里读取字符串](/contents/how-do-i-create-a-java-string-from-the-contents-of-a-file.md) -* [遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出](/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-reiterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md) +* [遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出](/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md) * [如何让IntelliJ编辑器永久性显示代码行数](/contents/how-can-i-permanently-have-line-numbers-in-intellij.md) * [如何使用maven把项目及其依赖打包为可运行jar包](/contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md) From c35cced4863cc655b7969534ad4138867a9fb6ef Mon Sep 17 00:00:00 2001 From: lizeyang Date: 2019年9月14日 15:58:48 +0800 Subject: [PATCH 105/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4580d52..6d711f0 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,10 @@ stackoverflow-Java-top-qa * [Java内部类和嵌套静态类](/contents/java-inner-class-and-static-nested-class.md) * [@Component, @Repository, @Service的区别](/contents/whats-the-difference-between-component-repository-service-annotations-in.md) * [如何创建泛型java数组](/contents/how-to-create-a-generic-array-in-java.md) +* [如何在整数左填充0](/contents/how-can-i-pad-an-integers-with-zeros-on-the-left.md) +* [Java里什么是与C++的Pair相等的?](/contents/what-is-the-equivalent-of-the-c++pair-in-java.md) +* [为什么数学函数Math.round(0.49999999999999994) 返回 1](/contents/why-does-math-round0-49999999999999994-return-1.md) +* [这段代码为什么陷入了死循环](/contents/why-does-this-go-into-an-infinite-loop.md) > 编程技巧 @@ -94,6 +98,11 @@ stackoverflow-Java-top-qa * [遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出](/contents/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re.md) * [如何让IntelliJ编辑器永久性显示代码行数](/contents/how-can-i-permanently-have-line-numbers-in-intellij.md) * [如何使用maven把项目及其依赖打包为可运行jar包](/contents/how-can-i-create-an-executable-jar-with-dependencies-using-maven.md) +* [重新导入项目到eclipse时遇到'Must Override a Superclass Method'报错](/contents/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips.md) +* [如何产生一个随机的字母数字串作为 session 的唯一标识符](/contents/how-to-generate-a-random-alpha-numeric-string.md) +* [Apache Camel是什么](/contents/what-exactly-is-apache-camel.md) +* [通过对象属性对常规对象的ArrayList进行排序](/contents/sort-arraylist-of-custom-objects-by-property.md) + > 网络 @@ -106,6 +115,7 @@ stackoverflow-Java-top-qa * [为什么处理排序的数组要比非排序的快](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-processing-a-sorted-array-faster-than-an-unsorted-array.md) * [如何使用Java创建一个内存泄漏的程序](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/creating-a-memory-leak-with-java.md) * [为什么打印"B"会明显的比打印"#"慢](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/why-is-printing-b-dramatically-slower-than-printing.md) +* ["Double Brace Initialization"的效率问题](/contents/efficiency-of-java-double-brace-initialization.md) > 测试 @@ -117,16 +127,14 @@ stackoverflow-Java-top-qa * [在Android里面下载文件,并在ProgressDialog显示进度](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog.md) * [如何获取Android设备唯一ID](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/is-there-a-unique-android-device-id.md) * [安装Android SDK的时候找不到JDK](contents/android-sdk-installation-doesnt-find-jdk.md) +* [安卓中"UserManger.isUserAGoat()"的合适案例](contents/proper-use-cases-for-android-usermanager-isuseragoat.md) + ### 待翻译问题链接(还剩x问题) -- [Proper use cases for Android UserManager.isUserAGoat()?](http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) -- ['Must Override a Superclass Method' Errors after importing a project into Eclipse](http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) -- [How to generate a random alpha-numeric string?](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) - [Failed to load the JNI shared Library (JDK)](http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk) -- [What exactly is Apache Camel?](http://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel) - [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) - [How do I discover memory usage of my application in Android?](http://stackoverflow.com/questions/2298208/how-do-i-discover-memory-usage-of-my-application-in-android) - [Uncatchable ChuckNorrisException](http://stackoverflow.com/questions/13883166/uncatchable-chucknorrisexception) @@ -135,14 +143,8 @@ stackoverflow-Java-top-qa - [Setting multiple jars in java classpath](http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath) - [What is the Java equivalent for LINQ?](http://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) -- [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) -- [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) -- [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) -- [Why does this go into an infinite loop?](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) - [decompiling DEX into Java sourcecode](http://stackoverflow.com/questions/1249973/decompiling-dex-into-java-sourcecode) -- [Why does Math.round(0.49999999999999994) return 1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1) - [Eclipse: Set maximum line length for auto formatting?](http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting) -- [What is the equivalent of the C++ Pair in Java?](http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java) - [How do I "decompile" Java class files?](http://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files) - [Useful Eclipse Java Code Templates [closed]](http://stackoverflow.com/questions/1028858/useful-eclipse-java-code-templates) - [How to call SOAP web service in Android](http://stackoverflow.com/questions/297586/how-to-call-soap-web-service-in-android) From 926e85d9bcd7e627f2f5eee63b508c98bd2f4b65 Mon Sep 17 00:00:00 2001 From: lizeyang Date: 2019年9月14日 16:25:03 +0800 Subject: [PATCH 106/108] =?UTF-8?q?=E9=83=A8=E5=88=86=E7=BF=BB=E8=AF=91?= =?UTF-8?q?=E6=B2=A1=E6=9C=89=E5=8A=A0stackoverlow=E5=8E=9F=E6=96=87?= =?UTF-8?q?=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 +- ...maximun-line-length-for-auto-formatting.md | 4 +- ...led-to-load-the-JNI-shared-library(JDK).md | 2 + .../how-do-i-decompile-java-class-files.md | 2 + ...setting-multiple-jars-in-java-classpath.md | 4 +- contents/what-the-equivalent-of-x=x++.md | 106 ------------------ .../why-does-this-go-into-an-infinite-loop | 2 - "345円244円207円345円277円230円.md" | 1 - 8 files changed, 14 insertions(+), 116 deletions(-) delete mode 100644 contents/what-the-equivalent-of-x=x++.md delete mode 100644 contents/why-does-this-go-into-an-infinite-loop delete mode 100644 "345円244円207円345円277円230円.md" diff --git a/README.md b/README.md index 6d711f0..447ce35 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,10 @@ stackoverflow-Java-top-qa * [如何产生一个随机的字母数字串作为 session 的唯一标识符](/contents/how-to-generate-a-random-alpha-numeric-string.md) * [Apache Camel是什么](/contents/what-exactly-is-apache-camel.md) * [通过对象属性对常规对象的ArrayList进行排序](/contents/sort-arraylist-of-custom-objects-by-property.md) - +* [为Eclipse自动代码格式化设置行的最大长度?](/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md) +* [加载JNI共享库失败(JDK)](/contents/failed-to-load-the-JNI-shared-library(JDK).md) +* [如何对Java class文件进行反编译](/contents/how-do-i-decompile-java-class-files.md) +* [如何在classpath中设置多个jar包](/contents/setting-multiple-jars-in-java-classpath.md) > 网络 @@ -134,18 +137,14 @@ stackoverflow-Java-top-qa - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) -- [Failed to load the JNI shared Library (JDK)](http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk) - [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) - [How do I discover memory usage of my application in Android?](http://stackoverflow.com/questions/2298208/how-do-i-discover-memory-usage-of-my-application-in-android) - [Uncatchable ChuckNorrisException](http://stackoverflow.com/questions/13883166/uncatchable-chucknorrisexception) - [Can I add jars to maven 2 build classpath without installing them?](http://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them) - [Update Eclipse with Android development tools v. 23](http://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-v-23) -- [Setting multiple jars in java classpath](http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath) - [What is the Java equivalent for LINQ?](http://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) - [Hibernate hbm2ddl.auto possible values and what they do?](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do) - [decompiling DEX into Java sourcecode](http://stackoverflow.com/questions/1249973/decompiling-dex-into-java-sourcecode) -- [Eclipse: Set maximum line length for auto formatting?](http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting) -- [How do I "decompile" Java class files?](http://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files) - [Useful Eclipse Java Code Templates [closed]](http://stackoverflow.com/questions/1028858/useful-eclipse-java-code-templates) - [How to call SOAP web service in Android](http://stackoverflow.com/questions/297586/how-to-call-soap-web-service-in-android) diff --git a/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md b/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md index b1f8579..d00fbae 100644 --- a/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md +++ b/contents/Eclipse-set-maximun-line-length-for-auto-formatting.md @@ -1,4 +1,6 @@ 为自动代码调整设置最大的行数? 问题:我正在学习Java。如果我在Eclipse Helios里使用ctrl+shift+f的组合键,它会自动调整我的代码。一定程度下,它会改变行数。我想增加行数的最大值。应该怎么做? -回答,在偏好设置里,分别点击Java->Code Style->Fomatter->edit,在菜单栏Line Wrapping下会有行的宽度选择(Maximun line width).你将需要编辑你的代码轮廓。 \ No newline at end of file +回答,在偏好设置里,分别点击Java->Code Style->Fomatter->edit,在菜单栏Line Wrapping下会有行的宽度选择(Maximun line width).你将需要编辑你的代码轮廓。 + +stackoverflow原址:http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting \ No newline at end of file diff --git a/contents/failed-to-load-the-JNI-shared-library(JDK).md b/contents/failed-to-load-the-JNI-shared-library(JDK).md index b60b2cd..8fffc87 100644 --- a/contents/failed-to-load-the-JNI-shared-library(JDK).md +++ b/contents/failed-to-load-the-JNI-shared-library(JDK).md @@ -14,4 +14,6 @@ Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`. ·64位的Java ·64位的Eclipse +- stackoverflow原址: +http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk diff --git a/contents/how-do-i-decompile-java-class-files.md b/contents/how-do-i-decompile-java-class-files.md index 8a28fc2..f050bdd 100644 --- a/contents/how-do-i-decompile-java-class-files.md +++ b/contents/how-do-i-decompile-java-class-files.md @@ -63,3 +63,5 @@ JAD JD-GUI真的很棒。你可以打开一个jar文件并浏览代码,就好像正在使用IDE一样。好东西。 +### 原文链接 +http://stackoverflow.com/questions/272535/how-do-i-decompile-java-class-files \ No newline at end of file diff --git a/contents/setting-multiple-jars-in-java-classpath.md b/contents/setting-multiple-jars-in-java-classpath.md index 6549e70..e87a69b 100644 --- a/contents/setting-multiple-jars-in-java-classpath.md +++ b/contents/setting-multiple-jars-in-java-classpath.md @@ -35,4 +35,6 @@ Unix平台与Windows平台基本一样,除了使用冒号 `:` 替代分号 `;` 在类加载进程中,通配符的扩展在早期完成,优先于程序main函数的调用,而不是在其后。每个包含通配符的类路径都被替换为所在目录下所有jar包的序列。例如,如果目录`foo`包含`a.jar`,`b.jar`以及`c.jar`,因此类路径`foo/*`被扩展为`foo/a.jar;foo/b.jar;foo/c.jar`,并且以上字符串被作为系统属性`java.class.path`的值。 -环境变量`CLASSPATH`与命令行选项-classpath或者-cp并没有什么不同。也就是说,通配符既可以应用于命令行`-classpath/-cp`选项中,也可以应用于环境变量`CLASSPATH`中。 \ No newline at end of file +环境变量`CLASSPATH`与命令行选项-classpath或者-cp并没有什么不同。也就是说,通配符既可以应用于命令行`-classpath/-cp`选项中,也可以应用于环境变量`CLASSPATH`中。 + +stackoverflow原地址:http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath \ No newline at end of file diff --git a/contents/what-the-equivalent-of-x=x++.md b/contents/what-the-equivalent-of-x=x++.md deleted file mode 100644 index 1857b40..0000000 --- a/contents/what-the-equivalent-of-x=x++.md +++ /dev/null @@ -1,106 +0,0 @@ -## x=x++最终x等于多少? -### 问题描述: -``` -public class Tests { - public static void main(String[] args) throws Exception { - int x = 0; - while(x<3) { - x = x++; - System.out.println(x); - } - } -} -``` -如上,程序会进入死循环,我们知道通常对于x自增是通过x++或者x=x+1,那么为什么x=x++不是对x自增再赋值给x? - -### 回答: -明确x=x++处理流程,相当于: -```java -int temp=x; -x++; -x=temp; -``` -#### 解释: -考虑如下类: -```java -class test { - public static void main(String[] args) { - int i=0; - i=i++; - } -} -``` -通过运行反汇编: -```bash -$ javap -c test -``` -可以得到: -```java -Compiled from "test.java" -class test extends java.lang.Object{ -test(); - Code: - 0: aload_0 - 1: invokespecial #1; //Method java/lang/Object."":()V - 4: return - -public static void main(java.lang.String[]); - Code: - 0: iconst_0 - 1: istore_1 - 2: iload_1 - 3: iinc 1, 1 - 6: istore_1 - 7: return -} -``` -以下来解释其中的助记符: -* iconst_0: 常量0被push入栈。 - -* istore_1: 栈顶元素被pop出,然后存储在索引为1的局部变量也就是x内。 - -* iload_1 : 索引为1的局部变量(即x)的值被push入栈,此时栈顶值为0。 - -* iinc 1, 1 :索引为1的量增加为1,也就是x变为1。 - -* istore_1 : 栈顶值被pop出,存入索引为1的局部变量中,因此x再次变为0。 - -以上,可以知道x=x++由于入栈出栈,x的值并未变化。 - -#### 对比:x=++x -```java -class test { - public static void main(String[] args) { - int i=0; - i=++i; - } -} -``` -运行 -```bash -$ javac test.java -$ javap -c test -``` -得到: -```java -Compiled from "test.java" -class test { - test(); - Code: - 0: aload_0 - 1: invokespecial #1 // Method java/lang/Object."":()V - 4: return - - public static void main(java.lang.String[]); - Code: - 0: iconst_0 - 1: istore_1 - 2: iinc 1, 1 - 5: iload_1 - 6: istore_1 - 7: return -} -``` -可以看出是先对x进行加一,再将x的值push入栈,随后再将栈顶值赋给x。 - - diff --git a/contents/why-does-this-go-into-an-infinite-loop b/contents/why-does-this-go-into-an-infinite-loop deleted file mode 100644 index 33787a9..0000000 --- a/contents/why-does-this-go-into-an-infinite-loop +++ /dev/null @@ -1,2 +0,0 @@ -## 为什么它会进入死循环 - diff --git "a/345円244円207円345円277円230円.md" "b/345円244円207円345円277円230円.md" deleted file mode 100644 index c2e3070..0000000 --- "a/345円244円207円345円277円230円.md" +++ /dev/null @@ -1 +0,0 @@ -就是不行了 From 35dfc6f8b8f3669e30205eb291af3e148406bd2f Mon Sep 17 00:00:00 2001 From: lizeyang Date: 2019年9月14日 16:26:02 +0800 Subject: [PATCH 107/108] =?UTF-8?q?=E6=9B=B4=E6=96=B0readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 447ce35..10f931c 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ stackoverflow-Java-top-qa * [安卓中"UserManger.isUserAGoat()"的合适案例](contents/proper-use-cases-for-android-usermanager-isuseragoat.md) -### 待翻译问题链接(还剩x问题) +### 待翻译问题链接(还剩 13 问题) - [Why is executing Java code in comments with certain Unicode characters allowed?](http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed) - [Fastest way to determine if an integer's square root is an integer](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer) - [How to fix: Unsupported major.minor version 51.0 error?](http://stackoverflow.com/questions/10382929/how-to-fix-unsupported-major-minor-version-51-0-error) From db68803d271ce43b7fdf4e42f6680154c91f3d9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=B3=BD=E6=89=AC?= <51961070@qq.com> Date: 2019年9月17日 08:31:00 +0800 Subject: [PATCH 108/108] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10f931c..e6c4632 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ stackoverflow-Java-top-qa 对于参与翻译的人,这也是很好的一个学习、理解过程,欢迎大家一起来翻译 ------------- -### 如何参与翻译(欢迎加入翻译组QQ群485011036) +### 如何参与翻译 #### 如何参与: - 请从下文"待翻译问题链接"中寻找你感兴趣的问答进行翻译。翻译好的问答,放到contents目录下,无需更新readme.md文档。之后提一个PR,我负责合并PR并更新到readme中。 - 另外,为了避免多人重复新翻译一个问题,你可以提issue,说明你计划翻译的问题及时间点,我可以先更新到下面的"未翻译问题"中,说明已有人领了这个问题。当然,也不一定要提issue,一般情况下,只要及时提pr,我及时审核,出现"撞车"的概率并不高。

AltStyle によって変換されたページ (->オリジナル) /