Recently I came across an interesting post:
var a = ??? ; if(a == 1 && a == 12){ console.log(a); }Copy the code
This is a question thrown out by the JS community. At first glance, this problem seems ridiculous. How could one variable satisfy both conditions?
But when I thought more about it, I realized that these kinds of questions are kind of interesting…
If that seems impossible to you, read along. You’ll also find it interesting
This article covers not only JS, but also Java and other languages
The body of the
Let’s try to solve this problem. If (a==1&&a==12) is true, then a cannot be an “ordinary variable”. It must have the ability to change values dynamically at execution time.
I. JS version
Given this starting point, can we assume that if we can re-implement methods similar to method A, this result seems to be achieved?
Here’s an answer:I guess those of you who work in Java or any other object-oriented language might be confused by this answer. But if you look at it, if you think about it, you might actually get some ideas from it.
Of course, there may be JS partners want to ask for answers, here happens to have written analysis, here will post his article address
After seeing the answer of JS, I have been thinking again along the way: is it possible to complete this equation in Java? Can only say that their “skill is too shallow” has not found the right solution… So I googled it for myself, and there was an answer from someone who had no time to waste, even a few versions of it:
Java version
Here is the direct answer, although not very close to the title, but it does show the clever:
Class cache = Integer.class.getDeclaredClasses()[0];
Field c = cache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] array = (Integer[]) c.get(cache);
// array[129] is 1
array[130] = array[129];
// Set 2 to be 1
array[131] = array[129];
// Set 3 to be 1
Integer a = 1;
if(a == (Integer)1 && a == (Integer)2 && a == (Integer)3){
System.out.println("Success");
}
Copy the code
The other answer, which is frankly more awesome, is:
PowerMockRunner is used here, which is also the most direct helper to solve the problem. The end of the
The purpose of writing this article is not to delve deeply into these language features, but simply to find them interesting.
If starting from the problem itself, it can examine the solver’s mastery of language characteristics; Also can examine the problem solver to treat the problem, try to solve the problem methodology. There is a long way to go to learn.
Source: www.toutiao.com/i6805578326…