The 10 most popular Java issues on Stack Overflow __java

Source: Internet
Author: User
turn from: http://www.codeceo.com/article/stackoverflow-10-java-problem.html 1, why Two (1927) time subtraction to get a strange result.

(3,623 compliments)

If you execute the following program, the program parses the two-interval 1-second date string 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 LD4-LD3 is not 1 (because I want the two time difference to be one second), but 353.

If you add a date string one second:

String STR3 = "1927-12-31 23:54:08";  
String STR4 = "1927-12-31 23:54:09";

The result of the 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

This is the Shanghai time zone, with a change on December 31.

Check out this site for details of Shanghai's 1927 time zone changes. 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, and it appears that Java parsed the latter time as the local date and time caused the difference. 2, Java is "reference pass" or "value delivery."

(2,480 compliments)

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

Give an explanation.

Solution

Java has always been a value pass. Unfortunately, they decided to refer to the pointer as a reference, so the newcomer was always dizzy. Because these references are also passed by value. 3. A problem with Java + + operator

(2223 praises)

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;

However i = i + j; Unable to compile, while i = j; can be compiled.

This means i + j; is actually a shorthand for i = (type of i) (i + j).

Solution

Some people always ask such questions, JLS has the answer. See §15.26.2 compound assignment operator. Extract:

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

An example, quoted from §15.26.2

[...] The following code is correct:

Short x = 3;
x + 4.6;

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

Short x = 3;
x = (short) (x + 4.6);

In other words, your hypothesis is correct. 4, the difference between HashMap and Hashtable?

(1769 compliments)

What is the difference between HashMap and Hashtable in Java?

Which is more efficient for use in non-multithreaded applications.

Solution

There are several different points of HashMap and HashTable in Java: HashTable is synchronized, but HashMap is not. This makes hashmap more suitable for non-multithreaded applications, because asynchronous objects are generally more efficient than synchronization objects. Hashtable does not allow null values and keys. HashMap allows a null key and a null value for a person. A subclass of HashMap is Linkedhashmap. So, if you want to predict the iteration order (the default insertion order), simply convert the HashMap to a linkedhashmap. It won't be so easy with Hashtable.

Because synchronization is not a problem for you, I recommend using HashMap. If synchronization becomes a problem, you may also want to see Concurrenthashmap. 5. (how to) read or turn a inputstream into a String

(1724 compliments)

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

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

What is the simplest way to convert InputStream into String.

Solution

Using the Apache Commons ioutils library to copy InputStream to StringWriter is a good way to do this:

StringWriter writer = new StringWriter ();
Ioutils.copy (InputStream, writer, encoding);
String thestring = writer.tostring ();

Even

Nb:does
not closed InputStream, you can use ioutils.closequietly for that//NOTE: Do not turn off InputStream, you may be using IOUTILS.CLOSEQ uietly
String thestring = ioutils.tostring (InputStream, encoding);

Alternatively, you can use Bytearrayoutputstream if you don't want to mix the stream and the writer. 6, why the password in Java first use char[] instead of string.

(1574 compliments)

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

When a string involves a password, it becomes a security threat. It's not easy to feel like using a char array.

Solution

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

After you use an array, you can explicitly erase 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, this is a security issue – but even if you use a char array, just narrow down the attacker's window that has the chance to get the password, which is the value for the type of attack that was made. 7, the best way to traverse HashMap

(1504 compliments)

What is the best way to traverse elements in HashMap.

Solution

This traverses the EntrySet:

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. 8. (How to) create ArrayList from array

(1468 compliments)

I have an array that initializes the following:

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

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

Solution

New Arraylist<element> (Arrays.aslist (array))
9, the production of a Java memory leak

(1478 compliments)

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

So how do you create a memory leak?

Solution

In pure Java, there is a good way to produce a real memory leak (by executing code that makes an object inaccessible but still exists in memory): The application produces a long-running thread (or accelerates the leak using a thread pool). A thread loads a class through an optional custom-class loader. The class allocates large memory (for example, New byte[1000000]), assigns a strong reference to a static field, and then stores its own reference to the threadlocal. Allocating additional memory is optional (it is enough to divulge the class instance), but this will speed up the leak work. The thread clears any custom class's or ClassLoader-loaded references. Repeat the above steps.

This is valid because the 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 class loader holds references to all loaded classes. This can make the leak even worse, as the class and class loads implemented by many JVMs directly allocate memory from the persistence Band (PermGen) and are not recycled by GC. 10. Use Java to generate random integer numbers in an interval

(1422 compliments)
I tried to generate a random integer using Java, but it 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 random number generated.

Solution

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

Import Java.util.Random;

public static int Randint (int min, int max) {

    int randomnum = new Random (). Nextint ((max-min) + 1) + min;

    return randomnum;
}

Please check the related Javadoc. In practice, the Java.util.Random class is always superior to java.lang.Math.random ().

Especially when the standard library has a direct API to do the job, there's no need to reinvent the wheel.

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.