复制构造函数帮助,尝试复制布尔数组。爪哇

发布于 2024-11-26 11:17:23 字数 1913 浏览 4 评论 0原文

我已经浏览了尽可能多的以前的问题,但从未见过将布尔数组作为变量的问题。

这是我的课程:

public class Register {

private boolean[] register;
private int length;

    //Normal constructor
public Register(int n) {

    if (n == 8 || n == 16 || n == 32 || n == 64) {

        length = n;
        register = new boolean[length];

        for (int i = 0; i < length; i++) {

            register[i] = false;
        }

    } else {

        throw new RegisterException(
                "A register can only contain 8, 16, 32, or 64 bits");
    }

}

// Creates a copy of reg (an existing Register)
public Register(Register reg) {

    length = reg.length;
    register = new boolean[reg.register.length];

    System.arraycopy(reg.register, 0, this.register, 0, reg.register.length);
}

在我的驱动程序中,我将“1101101”加载到register1中,但是当我这样做时: 寄存器register2 = new Register(register1);

并打印出我得到的两个结果:

0000000001101101

0000000000010110

不太确定发生了什么 哦,任何帮助将不胜感激,谢谢!

这是我的加载方法。我推迟把它放在这里,因为它可能很难阅读:

public void load(String binaryRep) {

    String allTheBits = binaryRep;
    int charPosition = 0;
    int loadLength;
    int binaryNum = 0;
    String index = "";
    String trimmedIndex = "";

    if (allTheBits.length() > 0 && allTheBits.length() <= length) {

        loadLength = allTheBits.length();

        for (int i = length - (loadLength); i < length; i++) {

            index = allTheBits.charAt(charPosition) + "";
            trimmedIndex = index.trim();
            binaryNum = Integer.parseInt(trimmedIndex);

            if (binaryNum == 1) {

                register[i] = true;

            } else if (binaryNum == 0) {

                register[i] = false;
            }

            charPosition++;

        }
    } else {
        throw new RegisterException("You can only load 0 - " + length
                + "bits.");
    }
}

I have looked through as many previous questions as possible but never saw a question that had a boolean array as a variable.

Here is my class:

public class Register {

private boolean[] register;
private int length;

    //Normal constructor
public Register(int n) {

    if (n == 8 || n == 16 || n == 32 || n == 64) {

        length = n;
        register = new boolean[length];

        for (int i = 0; i < length; i++) {

            register[i] = false;
        }

    } else {

        throw new RegisterException(
                "A register can only contain 8, 16, 32, or 64 bits");
    }

}

// Creates a copy of reg (an existing Register)
public Register(Register reg) {

    length = reg.length;
    register = new boolean[reg.register.length];

    System.arraycopy(reg.register, 0, this.register, 0, reg.register.length);
}

In my driver program i am loading "1101101" into register1, but when i do:
Register register2 = new Register(register1);

and print out both results i get:

0000000001101101

0000000000010110

Not really sure what is going on O.o any help would be appreciated, thanks!

This is my load method. i held off on putting it in here because it might be hard to read:

public void load(String binaryRep) {

    String allTheBits = binaryRep;
    int charPosition = 0;
    int loadLength;
    int binaryNum = 0;
    String index = "";
    String trimmedIndex = "";

    if (allTheBits.length() > 0 && allTheBits.length() <= length) {

        loadLength = allTheBits.length();

        for (int i = length - (loadLength); i < length; i++) {

            index = allTheBits.charAt(charPosition) + "";
            trimmedIndex = index.trim();
            binaryNum = Integer.parseInt(trimmedIndex);

            if (binaryNum == 1) {

                register[i] = true;

            } else if (binaryNum == 0) {

                register[i] = false;
            }

            charPosition++;

        }
    } else {
        throw new RegisterException("You can only load 0 - " + length
                + "bits.");
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

佼人 2024-12-03 11:17:23

这是一种更惯用的方法(使用 Cloneable 接口):

public class Register implements Cloneable {

private boolean[] register;

public Register(boolean[] register) {

    int n = register.length;

    if (n == 8 || n == 16 || n == 32 || n == 64) {
        this.register = register;
    } else {

        throw new IllegalArgumentException(
                "A register can only contain 8, 16, 32, or 64 bits");
    }

}

@Override
public String toString() {

    StringBuilder builder = new StringBuilder();

    for ( boolean b : this.register ) {
        builder.append( b ? "1" : "0" );
    }

    return builder.toString();
}

public Register( int n ) {
    this( new boolean[n] );
}

public int getLength() {
    return this.register.length;
}

@Override
public Register clone() {

    boolean[] clonedRegister = new boolean[this.register.length];

    System.arraycopy(this.register, 0, clonedRegister,0, this.register.length);

    return new Register( clonedRegister );
}

}

并且 JUnit 测试显示了它的实际效果:

import org.junit.Assert;
import org.junit.Test;


public class RegisterTest {

    @Test
    public void testRegisterToString() {

        Register source = new Register( new boolean[] {true, true, false, false, true, false, true, false } );

        String result = "11001010";

        Assert.assertEquals( result, source.toString() );

    }

    @Test
    public void testRegisterCloning() {

        Register source = new Register( new boolean[] {true, true, false, false, true, false, false, false } );
        Register clone = source.clone();

        Assert.assertEquals( source.toString(), clone.toString() );

    }

}

Here's a more idiomatic way of doing it (using the Cloneable interface):

public class Register implements Cloneable {

private boolean[] register;

public Register(boolean[] register) {

    int n = register.length;

    if (n == 8 || n == 16 || n == 32 || n == 64) {
        this.register = register;
    } else {

        throw new IllegalArgumentException(
                "A register can only contain 8, 16, 32, or 64 bits");
    }

}

@Override
public String toString() {

    StringBuilder builder = new StringBuilder();

    for ( boolean b : this.register ) {
        builder.append( b ? "1" : "0" );
    }

    return builder.toString();
}

public Register( int n ) {
    this( new boolean[n] );
}

public int getLength() {
    return this.register.length;
}

@Override
public Register clone() {

    boolean[] clonedRegister = new boolean[this.register.length];

    System.arraycopy(this.register, 0, clonedRegister,0, this.register.length);

    return new Register( clonedRegister );
}

}

And a JUnit test showing it in action:

import org.junit.Assert;
import org.junit.Test;


public class RegisterTest {

    @Test
    public void testRegisterToString() {

        Register source = new Register( new boolean[] {true, true, false, false, true, false, true, false } );

        String result = "11001010";

        Assert.assertEquals( result, source.toString() );

    }

    @Test
    public void testRegisterCloning() {

        Register source = new Register( new boolean[] {true, true, false, false, true, false, false, false } );
        Register clone = source.clone();

        Assert.assertEquals( source.toString(), clone.toString() );

    }

}
何止钟意 2024-12-03 11:17:23

一些评论,以便您了解一些基本知识。

  1. 正如@Ted所说,不需要将长度字段保留为寄存器。 length 会给你相同的
  2. 局部变量没有用默认值初始化,但数组是,因为它们存储在堆中。因此,无需迭代“寄存器”数组以将其所有位置设置为 false
  3. 使用布尔数组来执行此操作可能感觉很简单,但其内存效率极低,因为每个布尔值在堆中至少占用 32 位。因此,要表示 64 位寄存器,您至少使用 32*64+32=2080 位...使用字节数组和按位逻辑会有点困难,但是嘿,这是一个小挑战:)

无论如何,您的代码看起来很好(顺便说一句,使用 Arrays.copyOf 方法,因为它更具可读性),所以错误应该来自另一边。

A couple of remarks so that you learn some basic things.

  1. As @Ted said, no need to keep the length field as register. length will give you the same
  2. Local variables are not initialized with default values, but arrays are, as they are stored in the heap. So there's no need to iterate over the "register" array to set all of its positions to false
  3. Using an array of booleans to do this may have felt easy but its extremely inefficient memory wise, as each boolean takes at least 32 bits in the heap. Therefore, to represent a 64 bit register you are using at least 32*64+32=2080 bits... using a byte array and bitwise logic will be a bit harder but hey, it's a small challenge :)

Anyway, your code looks fine (BTW, use Arrays.copyOf method as it's more readable), so the error should be coming from another side.

墨落成白 2024-12-03 11:17:23

我刚刚使用以下内容验证了您的加载方法:

public static void main(String [] args)
{
    Register r1 = new Register(8);
    r1.load("1101101");
    Register r2 = new Register(r1);
    for (int i=0; i<8; i++) System.out.println(r2.register[i]);
}

输出:

> run Register
false
true
true
false
true
true
false
true
> 

就 Register 对象的内容而言,它在我看来是正确的,因此问题可能在于访问。

I just verified your load method with the following:

public static void main(String [] args)
{
    Register r1 = new Register(8);
    r1.load("1101101");
    Register r2 = new Register(r1);
    for (int i=0; i<8; i++) System.out.println(r2.register[i]);
}

Output:

> run Register
false
true
true
false
true
true
false
true
> 

It looks right to me as far as the contents of the Register objects are concerned, so the problem probably is with the access.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文