The 10 most popular Java issues on the StackOverflow

Source: Internet
Author: User
Tags locale

1, why two (1927) time subtraction to get a strange result?

(3,623 likes)

If you execute the following program, the program resolves a two-second date string that is 1 seconds apart and compares:

12345678910 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);}

The output is:

1 353

Why is ld4-ld3 not 1 (because I hope the two time difference is one second), but 353?

If you add a second to the date string:

12 String str3 = "1927-12-31 23:54:08"String str4 = "1927-12-31 23:54:09";

The result of LD4-LD3 is 1.

1234567 sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]Locale(Locale.getDefault()): zh_CN

Solution Solutions

This is the Shanghai time zone, and there was a change on December 31.

Check out this website for details of the time zone changes in Shanghai in 1927. Basically at midnight at the end of 1927, 5 minutes and 52 seconds will always be dialed back. So "1927-12-31 23:54:08" actually happened two times, it seems that Java parsed the latter time as the local date and time caused the difference.

2. Is Java "reference passing" or "value passing"? (2,480 likes)

I always thought Java was a reference pass ; however, I looked at a bunch of blogs (for example, this one) claiming it was not. I don't think I understand the difference between them.

Give an explanation?

Solution Solutions

Java has always been a value pass . Unfortunately, they decided to call the pointer a reference, so the newcomer was always dizzy. Because these references are also passed by value.

3. A question about the Java + = operator

(2223 likes)

Until today I think this example:

1 i += j;

It's just a shorthand:

1 i = i + j;

But if you do this:

12 inti = 5;longj = 8;

i = i + j however; Unable to compile, and i + = j; You can compile it.

Does that mean it's i += j; actually i = (type of i) (i + j) shorthand?

Solution Solutions

There are always people asking such questions, and there are answers in JLS. See §15.26.2 compound assignment operator. Extract:

The compound assignment expression for the E1 op= E2 type is equivalent to E1 = (t) ((E1) op (E2)), where T is the type of E1, except that E1 is calculated only once.

An example quoted by §15.26.2

[...] The following code is correct:

12 shortx = 3;x += 4.6;

The result of X is equal to 7 because it is equivalent to:

12 shortx = 3;x = (short)(x + 4.6);

In other words, your hypothesis is correct.

4, the difference between HashMap and Hashtable? (1769 likes)

In Java HashMap andHashtable的不同是什么?

Which is more efficient to use in non-multithreaded applications?

Solution Solutions

There are several different points in Java for HashMap and HashTable:

    1. HashtableIs synchronous, however HashMap not. This makes the HashMap more suitable for non-multithreaded applications because non-synchronous objects typically perform more efficiently than synchronous objects.
    2. Hashtable null values and keys are not allowed. HashMap allows a null key and a null value for a person.
    3. A subclass of HashMap isLinkedHashMap。所以,如果想预知迭代顺序(默认的插入顺序),只需将HashMap转换成一个LinkedHashMap。用Hashtable就不会这么简单。

Because syncing is not a problem for you, I recommend using HashMap. If syncing becomes a problem, you may want to look atConcurrentHashMap。

5. (How to) read or turn a inputstream into a String (1724 likes)

If you have a Java.io.InputStream object, such as processing this object and generating a string?

Suppose I have an InputStream object that contains textual data, and I want to convert it into a string (for example, so I can write the contents of the stream into a log file).

InputStreamWhat is the simplest way to convert to a String?

Solution Solutions

Using Apache Commons is IOUtils库来拷贝InputStream到StringWriter是一种 a good way to do something like this:

123 StringWriter writer = newStringWriter();IOUtils.copy(inputStream, writer, encoding);String theString = writer.toString();

Even

123 // NB: does not close inputStream, you can use IOUtils.closeQuietly for that// 注意:不关闭inputStream,你可以使用 IOUtils.closeQuietlyString theString = IOUtils.toString(inputStream, encoding);

Or, if you don't want to mix stream and writer, you can useByteArrayOutputStream。

6. Why is the password in Java preferred using char[] instead of string? (1574 likes)

In swing, the password field has a GetPassword () (return char array) method instead of the usual gettext () (return string) method. Similarly, I've come across a recommendation not to use String to handle passwords.

Why does string involve a password when it becomes a security threat? Feel that using a char array is not convenient.

Solution Solutions

The string is immutable. This means that once a string is created, if another process can make a memory dump, there is no way to purge the string data (except for reflection) before the GC occurs.

After using an array operation, you can explicitly purge the data: You can assign any value to the array, the password will not exist in the system, or even before garbage collection.

So, yes, it's a security issue – but even with a char array, only the window that the attacker has the opportunity to get the password is narrowed, and it's worth the type of attack.

7. The best way to traverse HashMap

(1504 likes)

What is the best way to traverse elements in HashMap?

Solution Solutions

This traversalentrySet:

12345678 public static void printMap(Map mp) {    Iterator it = mp.entrySet().iterator();    while (it.hasNext()) {        Map.Entry pair = (Map.Entry)it.next();        System.out.println(pair.getKey() + " = " + pair.getValue());        it.remove(); // avoids a ConcurrentModificationException    }}

Please refer to map for more information.

8. (How to) create a ArrayList from an array (1468 likes)

I have an array, initialized as follows:

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

I want to convert this array into an object of the ArrayList class.

Solution Solutions

1 newArrayList<Element>(Arrays.asList(array))
9. Generate a Java memory leak

(1478 likes)

I had an interview and was asked how to generate a Java memory leak. Needless to say, I felt rather silly, and even how to produce a clue to none.

So how do you generate a memory leak?

Solution Solutions

In pure Java, there is a good way to create a true memory leak (by executing code that makes the object inaccessible but still exists in memory):

    1. The application generates a long-running thread (or uses a thread pool to speed up the leak).
    2. The thread loads a class through an (optional) class loader.
    3. This class allocates large memory (for example, New byte[1000000]), assigns a strong reference to a static field, and then stores its own reference to threadlocal. Allocating additional memory is optional (leaking class instances is enough), but this will speed up the leak effort.
    4. The thread clears all custom classes or the ClassLoader-loaded references.
    5. Repeat the above steps.

This is valid because threadlocal holds a reference to the object, the object holds a reference to the class, and then the class holds a reference to the ClassLoader. in turn, the ClassLoader holds references to all loaded classes. This makes the leak even more severe because many JVM-implemented classes and class loads allocate memory directly from the persistence Band (PermGen), and thus are not recycled by GC.

10, using Java to generate a random number of integers within a range

(1422 likes)

I tried to generate a random integer using Java, but was randomly assigned to a range. For example, the integer range is 5~10, which means that 5 is the smallest random value and 10 is the largest. A book from 5 to 10 can also be a generated random number. Solution Solutions

The standard solution (before Java1.7) is as follows:

123456789 import java.util.random;  public static int randint ( int min, int max) {   &NBSP;&NBSP;&NBSP;&NBSP; random Rand; &NBSP;&NBSP;&NBSP;&NBSP; int randomnum = Rand.nextint ((max-min) + 1 ) + min;  &NBSP;&NBSP;&NBSP;&NBSP; return randomnum; }

Please check the relevant Javadoc. In practice, the Java.util.Random class is always better than java.lang.Math.random ().

Especially when there is a direct API in the standard library to do this, there is no need to reinvent the wheel.

The 10 most popular Java issues on the StackOverflow

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.