This article is translated by Importnew-liken from Nolsit. Welcome to join the translation team. Reproduced please see at the end of the request.
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:
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:
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:
String STR3 = "1927-12-31 23:54:08"= "1927-12-31 23:54:09";
The result of LD4-LD3 is 1.
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:
i + = j;
It's just a shorthand:
i = i + j;
But if you do this:
int i = 5; long j = 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:
Short x = 3+ = 4.6;
The result of X is equal to 7 because it is equivalent to:
Short x = 3= (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:
Hashtable
Is 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.
- Hashtable null values and keys are not allowed. HashMap allows a null key and a null value for a person.
- A subclass of HashMap is
LinkedHashMap。所以,如果想预知迭代顺序(默认的插入顺序),只需将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).
InputStream
What 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:
New= writer.tostring ();
Even
// nb:does not close InputStream, you can use the ioutils.closequietly for that // Note: Do not close inputstream, you can use ioutils.closequietly String 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:
Public Static void Printmap (Map MP) { = mp.entryset (). iterator (); while (It.hasnext ()) { = (map.entry) It.next (); + "=" + Pair.getvalue ()); // avoids a concurrentmodificationexception }}
For more information, please check Map.
8. (How to) create a ArrayList from an array (1468 likes)
I have an array, initialized as follows:
Element[] Array = {new New New Element (3)};
I want to convert this array into an object of the ArrayList class.
Solution Solutions
New Arraylist<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):
- The application generates a long-running thread (or uses a thread pool to speed up the leak).
- The thread loads a class through an (optional) class loader.
- 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.
- The thread clears all custom classes or the ClassLoader-loaded references.
- 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:
Importpublicstaticint randint (intint max) { Random Rand; int randomnum = Rand.nextint ((max-min) + 1) + min; 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.
Original link: Nolsit translation: Importnew.com-liken
Link: http://www.importnew.com/16841.html
[ Reprint please keep the source, translator and translation links.] ]
The 10 most popular Java issues on the StackOverflow