Java:如何通过引用传递byte []? [英] Java: How to pass byte[] by reference?

查看:202
本文介绍了Java:如何通过引用传递byte []?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用关键字ref在.NET中执行此操作。有没有办法在Java中这样做?

You can do it in .NET by using the keyword "ref". Is there any way to do so in Java?

推荐答案

你在做什么方法?如果您只是填充现有数组,那么您不需要传递引用语义 - 无论是在.NET中还是在Java中。在这两种情况下,引用都将按值传递 - 因此调用者可以看到对象的更改。这就像告诉别人你的房子的地址,并要求他们提供一些东西 - 没问题。

What are you doing in your method? If you're merely populating an existing array, then you don't need pass-by-reference semantics - either in .NET or in Java. In both cases, the reference will be passed by value - so changes to the object will be visible by the caller. That's like telling someone the address of your house and asking them to deliver something to it - no problem.

如果你真的想要传递 - 参考语义,即调用者将看到对参数本身所做的任何更改,例如将它设置为null或引用不同的字节数组,然后任一方法需要返回新值,或者您需要将引用传递给某种holder,其中包含对字节数组的引用,并且可以具有稍后从中获取的(可能已更改的)引用。

If you really want pass-by-reference semantics, i.e. the caller will see any changes made to the parameter itself, e.g. setting it to null or a reference to a different byte array, then either method needs to return the new value, or you need to pass a reference to some sort of "holder" which contains a reference to the byte array, and which can have the (possibly changed) reference grabbed from it later.

换句话说,如果您的方法看起来像这样:

In other words, if your method looks likes this:

public void doSomething(byte[] data)
{
    for (int i=0; i < data.length; i++)
    {
        data[i] = (byte) i;
    }
}

然后你很好。如果您的方法如下所示:

then you're fine. If your method looks like this:

public void createArray(byte[] data, int length)
{
    // Eek! Change to parameter won't get seen by caller
    data = new byte[length]; 
    for (int i=0; i < data.length; i++)
    {
        data[i] = (byte) i;
    }
}

然后您需要将其更改为:

then you need to change it to either:

public byte[] createArray(int length)
{
    byte[] data = new byte[length]; 
    for (int i=0; i < data.length; i++)
    {
        data[i] = (byte) i;
    }
    return data;
}

或:

public class Holder<T>
{
    public T value; // Use a property in real code!
}

public void createArray(Holder<byte[]> holder, int length)
{
    holder.value = new byte[length]; 
    for (int i=0; i < length; i++)
    {
        holder.value[i] = (byte) i;
    }
}

有关详细信息,请阅读参数传递C#用Java传递参数。 (前者写得比后者好,我很害怕。有一天我会回来做更新。)

For more details, read Parameter passing in C# and Parameter passing in Java. (The former is better written than the latter, I'm afraid. One day I'll get round to doing an update.)

这篇关于Java:如何通过引用传递byte []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆