小编Ank*_*and的帖子

如何在Java中完成最终字符串的连接?

当我编译这个片段.

public class InternTest {
    public static void main(String...strings ){
        final String str1="str";
        final String str2="ing";
        String str= str1+str2;

    }
}
Run Code Online (Sandbox Code Playgroud)

其中产生以下字节代码

public static void main(java.lang.String...);
   flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
   Code:
     stack=1, locals=4, args_size=1
        0: ldc           #16                 // String str
        2: astore_1
        3: ldc           #18                 // String ing
        5: astore_2
        6: ldc           #20                 // String string
        8: astore_3
        9: return
Run Code Online (Sandbox Code Playgroud)

所以字符串文字"字符串"已存在于常量池中,该字符串6: ldc #20 // String string在此行的堆栈上被推送.

引用JSL

来自JLS§4.12.4 - 最终变量:

原始类型或类型String的变量是final,并使用编译时常量表达式(第15.28节)初始化,称为常量变量.

同样来自JLS§15.28 - ConstantExpression:

String类型的编译时常量表达式总是"实例化",以便使用String#intern()方法共享唯一的实例.

所以我知道str1和str2将在创建时被实现."str"和"ing"将在行共享相同的内存String str= …

java string final

17
推荐指数
1
解决办法
4396
查看次数

如何计算函数的空间复杂度?

我理解基本的,如果我有这样的功能:

int sum(int x, int y, int z) {
  int r = x + y + z;
  return r;
}
Run Code Online (Sandbox Code Playgroud)

它需要3个单位的空间用于参数,1个用于局部变量,这永远不会改变,所以这是O(1).

但是,如果我有这样的功能怎么办:

void add(int a[], int b[], int c[], int n) {
    for (int i = 0; i < n; ++i) {
        c[i] = a[i] + b[0]
    }
}
Run Code Online (Sandbox Code Playgroud)

其中需要N个单位a,M个单位为bL个单位c,1个单位为in.所以它需要N+M+L+1+1大量的存储空间.

那么这里的空间复杂性大O会是什么?需要更高记忆的那个?也就是说,如果N比M和L更高的momery(从更高的意义上假设大于10**6) - 那么可以说空间复杂性是否O(N)与我们对时间复杂性的影响一样?

但是如果所有三个即a,b,c都没有太大差异

喜欢这个功能

void multiply(int a[], int b[], int c[][], …
Run Code Online (Sandbox Code Playgroud)

algorithm space-complexity

14
推荐指数
2
解决办法
1万
查看次数

Mocha如何知道在测试套件中首先加载哪个文件

我正在尝试用MongodB学习A测试驱动方法.文件夹结构

在此输入图像描述

A user.js在src文件夹中测试

const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Schema = mongoose.Schema;

const UserSchema = new Schema ({
    name: String
});

const User = mongoose.model('user', UserSchema);

module.exports = User;
Run Code Online (Sandbox Code Playgroud)

内容 test_helper.js

const mongoose = require('mongoose');;

mongoose.connect('mongodb://localhost/users_test');

    mongoose.connection
    .once('open', () => {
        console.log('Connected to Mongo!');
        done()}) 
    .on('error', (error) => { 
        console.warn('Warning', error);
    });
Run Code Online (Sandbox Code Playgroud)

create_test.js 内容

const assert = require('assert');
const User = require('../src/user');

describe('Creating records', () => {

    it('Saves a user', (done) => {
        const user = new …
Run Code Online (Sandbox Code Playgroud)

javascript testing mocha.js mongodb node.js

7
推荐指数
1
解决办法
1704
查看次数

如何在Node.js expressjs中处理异步对象方法中的未处理的promise拒绝?

我使用对象内的异步函数在express.js中发送响应

控制器代码:

module.exports = {

    async signUpEmail(req, res) {

        /**
         * @description Parameters from body
         * @param {string} firstName - First Name
         * @inner
         */  

        const firstName = req.body.firstName;

        res.send({ success: name });
        throw new Error(); // purposely Done
    }
}
Run Code Online (Sandbox Code Playgroud)

题:

由于signUpEmail方法在我的情况下是异步的,并且它将被拒绝,无论我的异步方法扔在这里它都来了Error.(故意放在那里)

所以记录在控制台中.

(node:13537) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error
(node:13537) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit …
Run Code Online (Sandbox Code Playgroud)

javascript node.js express async-await ecmascript-2017

7
推荐指数
1
解决办法
2775
查看次数

java中内部静态类的构造函数?

我写了下面的代码

public class Reader1 {
    private int pageNumber;

    private class ReaderName1{
        public int getPage(){
        return pageNumber;
        }
    }
    static class ReaderFound{

    }
}
Run Code Online (Sandbox Code Playgroud)

当我在已编译的代码上使用Java类文件反汇编程序javap时

1. for Reader1.class



class Reader1$ReaderName1 {
              final Reader1 this$0;
              private Reader1$ReaderName1(Reader1);
              public int getPage();
            }


2. for Reader1$ReaderName1.class



    public class Reader1 {
          private int pageNumber;
          public Reader1();
          static int access$000(Reader1);
        }

3. for Reader1$ReaderFound.class



     class Reader1$ReaderFound {
          Reader1$ReaderFound();
        }
Run Code Online (Sandbox Code Playgroud)

我的问题是,因为ReaderFound是一个静态类,它怎么能有一个默认的构造函数?如果是这样的话?是允许的吗?

如果允许在Reader1 $ ReaderFound类中找到什么样的构造函数,因为它不能是静态的.(此外,由于构造函数被隐式调用以初始化一个对象,因为ReaderFound是一个静态类,所以我们没有它的对象.我对第一个问题的观点)

java oop javap

6
推荐指数
1
解决办法
3103
查看次数

Java确定方法如何在运行时调用多态?

虽然多态性的主要原则是将"什么与谁"脱钩types,但令我困惑的是方法调用机制如何找出并在多态中调用正确的方法体.

因为在java中,所有方法绑定都是late-binding除非方法是static,final或者private,并且后期绑定由JVM完成,JVM method table为每个类预先计算,然后在正常方法调用的运行时期间查找表.

但同样的事情也发生在多态性中.例如

假设我有一个Cycle带有ride()方法的Generic类

class Cycle {

    public void ride(){
        System.out.println("I'm Riding generic Cycle()");
    }

}
Run Code Online (Sandbox Code Playgroud)

我有三个Specialized Class Bicycle Tricycle,Unicycle它扩展了Generic类Cycle并覆盖了它的ride()方法.

class Bicycle extends Cycle {

    public void ride() {
        System.out.println("I'm riding Bicycle");

    }

}

class Tricycle extends Cycle{

    public void ride() {
        System.out.println("I'm riding Tricycle ");

    }

}

class Unicycle extends Cycle {

    public void ride() …
Run Code Online (Sandbox Code Playgroud)

java polymorphism jvm bytecode

6
推荐指数
1
解决办法
1329
查看次数

如何在没有Joda Time的情况下在Java 7中正确处理夏令时?

在标记之前重复读取它彻底Plus不能使用Joda Time和Java 8 time.util*.

我正在尝试获取启用了DST的国家/地区的当前日期.因为它有时区,[local-millis] = [UTC-millis] + [offset-millis]所以我添加了DST_OFFSET它以获得启用DST的国家的时间,就像在Linux机器GMT_TIME + LOCAL_TIME_ZONE_OFFSET + DST_OFFSET上完成以获得当前的本地时间.

打印当前DST启用时间为1小时的当前伊斯坦布尔时间的代码.

public class DstInstanbul {

    public static void main(String...args){

        Calendar calendar = Calendar.getInstance();

        TimeZone timeZone = TimeZone.getTimeZone("Europe/Istanbul");

        calendar.setTimeZone(timeZone);

        calendar.add(Calendar.MILLISECOND, timeZone.getDSTSavings());


        SimpleDateFormat simpleDateFormatLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormatLocal.setTimeZone(TimeZone.getTimeZone("Europe/Istanbul"));

        System.out.println("Current date and time : " + simpleDateFormatLocal.format(calendar.getTime()));


       System.out.println("Current date and time : " + simpleDateFormatLocal.format(calendar.getTime()));
       System.out.println("The TimeZone is : " + calendar.getTimeZone().getID());

    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我正确的输出

Current date and time : …
Run Code Online (Sandbox Code Playgroud)

java timezone datetime calendar dst

5
推荐指数
1
解决办法
3025
查看次数

为什么打印整数数组对象给出哈希代码而char数组对象在java中给出值?

这是代码的片段

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char[] a={'a','b','c',97,'a'};
        System.out.println(a);
        int[] a1={8,6,7};
        System.out.println(a1);
        Integer[] b={10,20,30};
        System.out.println(b);
        }
}
Run Code Online (Sandbox Code Playgroud)

这是输出

abcaa
[I@239d5fe6
[Ljava.lang.Integer;@5527f4f9
Run Code Online (Sandbox Code Playgroud)

我知道它必须处理toString()方法.它已在char中重写以返回值.因此我们得到的第一个输出正如预期的那样是被重写的toString()方法java.lang.Character..

public String toString() {
      char buf[] = {value};//The value of the Character.
      return String.valueOf(buf);
   }
Run Code Online (Sandbox Code Playgroud)

但是看看Integer还有被覆盖的toString()方法

public String toString() {
        return String.valueOf(value); //The value of the Integer.
     }
Run Code Online (Sandbox Code Playgroud)

那么为什么打印a1和b代码会调用toString()Object类的默认实现,即:

public String toString() {
    return getClass().getName() + "@" + …
Run Code Online (Sandbox Code Playgroud)

java arrays

4
推荐指数
1
解决办法
633
查看次数

Java - 如何清除文本文件而不删除它?

我想知道清除文件的最佳方法是什么.我知道java会自动创建一个文件

f = new Formatter("jibberish.txt");  
s = new Scanner("jibberish.txt");
Run Code Online (Sandbox Code Playgroud)

如果都不存在 但是,如果一个存在并且我想在每次运行程序时清除它会怎么样?这就是我想知道的:再次说出如何清除已存在的文件只是空白?这就是我的想法:

public void clearFile(){
    //go through and do this every time in order to delete previous crap
    while(s.hasNext()){
        f.format(" ");
    }
} 
Run Code Online (Sandbox Code Playgroud)

java file formatter clear

4
推荐指数
3
解决办法
4万
查看次数

在没有尾随零的情况下有效地计算阶乘?

我正在努力改善大数的因子计算的运行时间.

第一个简单循环和乘法的代码.

def calculate_factorial_multi(number):
    '''
    This function takes one agruments and
    returns the factorials of that number


    This function uses the approach successive multiplication

    like 8! = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
    '''

    '''
    If 0 or 1 retrun immediately
    ''' 
    if number == 1 or number == 0:
        return 1

    result = 1 # variable to hold the result

    for x in xrange(1, number + 1, 1):
        result *= …
Run Code Online (Sandbox Code Playgroud)

python algorithm optimization profiling factorial

4
推荐指数
1
解决办法
418
查看次数

为什么同一个Go Channel无法启动两次?

我们可以在Go lang两次启动一个十分水平通道吗?

package main

import (
    "fmt"
)

func emit(c chan string) {

    words := []string {"The", "quick", "brown", "fox"}

    for _, word := range  words {
        c <- word
    }
    close(c)
}
Run Code Online (Sandbox Code Playgroud)

在函数main中如果我尝试使用相同的通道两次,我将获得该通道的默认值

func main() {

    wordChannel := make(chan string)

    go emit(wordChannel)

    for word := range wordChannel {
        fmt.Printf("%s ", word)
    }

    go emit(wordChannel)
    word1 := <-wordChannel
    fmt.Printf("%s" , word1) // prints Default value
}
Run Code Online (Sandbox Code Playgroud)

产量

所以再次使用它我要声明另一个频道.如果这不是错误,为什么在Go Lang中完成.?我正在使用go -lang 1.6版

channel go goroutine

2
推荐指数
1
解决办法
270
查看次数

java中的内部类和封闭实例?

在阅读 java Doc 时,我得到了以下内容。

  1. 如果 O 是 C 的直接词法封闭类并且 C 的声明未出现在静态上下文中,则内部类 C 是类 O 的直接内部类

所以如果我写

public class O{
    class Inner1{
        //
    }
    class Inner2{

    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是在这两个内部类中,哪一个是 O 的直接内部类?

我也得到了一些要点。

2.如果类 O 是 C 的第 n-1 个词法封闭类的直接封闭类,则它是类 C 的第 n 个词法封闭类。

3. 类 O 的直接内部类 C 的实例 i 与 O 的实例关联,称为 i 的直接封闭实例。对象的直接封闭实例(如果有)在创建对象时确定。

4. 对象 o 是其自身的第零个词法封闭实例。

5. 如果对象 o 是 i 的第 n-1 个词法封闭实例的直接封闭实例,则它是实例 i 的第 n 个词法封闭实例。

6. 其声明发生在静态上下文中的内部类 I 的实例没有词法上封闭的实例。但是,如果 I 立即在静态方法或静态初始化程序中声明,那么 I 确实有一个封闭块,它是词法上封闭 I 声明的最内层块语句。 …

java class

1
推荐指数
1
解决办法
310
查看次数