小编Jor*_*ein的帖子

如何在不复制对象的情况下将字符串转换为char []?

我有一个字符串,我需要将其作为char数组遍历.当然通常的方法是使用toCharArray()

String str = "Hello";
char[] charArr = str.toCharArray();
Run Code Online (Sandbox Code Playgroud)

现在,toCharArray()的源代码如下.

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

因此,Java在char []类型的内存中创建一个新对象,并将字符串对象复制到新对象.

我的问题是,是否可以在不复制数组的情况下将字符串用作char [].我的目的是节省内存空间.如果不可能,有这样的理由吗?

提前致谢!

java string char java-8

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

使用Jest和React模拟非默认函数

在测试文件中,我需要渲染一个组件,同时模拟它的一些子组件.文件结构看起来像这样松散.

档案1

import {A, B} from 'a-module';

export function MyComponent() {
    return (
        <div>
            <A /> // I need to mock
            <B /> // these components out
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

档案2

import {MyComponent} from 'File 1';

/*
 * In this file I would like to render MyComponent but
 * have components A and B be replaced by mocks
 */
Run Code Online (Sandbox Code Playgroud)

我已经尝试过,jest.mock('a-module', () => 'Blah');但这并没有成功地模拟组件.但是,在文件1中使用默认导入时,这会有效.

在模拟组件A和在文件2中B渲染时的任何帮助MyComponent都将非常感激!

javascript unit-testing reactjs webpack jestjs

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

将标准输出重定向到文件时,Windows 上的 Python“处理无效”

我正在尝试修复的脚本使用以下范例将标准输出重定向到文件。

import os
stdio_file = 'temp.out'
flag = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
stdio_fp = os.open(stdio_file, flag)
os.dup2(stdio_fp, 1)
print("hello")
Run Code Online (Sandbox Code Playgroud)

在 Python 2 上,这有效。在 Python 3 上,你得到一个 OSError

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print("hello")
OSError: [WinError 6] The handle is invalid
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
OSError: [WinError 6] The handle is invalid
Run Code Online (Sandbox Code Playgroud)

我认为有更可取的方法通过文件路由标准输出,但我想知道为什么这种方法在 Python 3 中停止工作,是否有一种简单的方法来修复它?

python windows operating-system python-3.x

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