二维数组在Java中,通过人物索引 [英] 2D Array in Java, Indexed by Characters

查看:132
本文介绍了二维数组在Java中,通过人物索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非我弄错了,这是合法的,有在Java中通过字符值索引的数组,因为这些是相当于8位数字。但是,下面的code生成我的错误信息:

Unless I'm mistaken, it is legal to have an array in Java indexed by character values, since these are equivalent to 8-bit numbers. However, the following code generates error messages for me:

int[][] myArray = new int[256][256];
myArray['%']['^'] = 25;

有没有一种方法,使这项工作?

Is there a way to make this work?

修改:哇,我真的没有做复制做好在code

edit: Wow, I really didn't do a good job of copying over the code.

推荐答案

这不是非法的,因为在Java中(和其他语言),在这种情况下,字符将被强制转换为一个int。如(int)的'%'

It is not illegal because in Java (and other languages), the char in this case will be casted to an int. Such as (int)'%'

这样的事情可能会更安全,如果你不知道它是什么类型char值。

Something like this would be safer if you don't know what type of char value it will be.

int[][] myArray = new int[Character.MAX_VALUE][Character.MAX_VALUE];
myArray['%']['^'] = 24;

自从Java它将工作将那意思就是:

It will work since Java will translate that to:

myArray[37][94] = 24;

请确保您将字符的最大值(如已经完成),它基本上是,?这相当于65535或者你会得到一个 ArrayOutOfBoundsException

Make sure you place max value of char (as already done) which is basically, '?' which translates to 65535. Or you will get an ArrayOutOfBoundsException.

如果你知道你的范围,你仍然可以使用256只要确保你做正确的边界检查该输入是> = 0和< 256。

If you know your range, you can still use 256. Just make sure you do proper bounds checking where the input is >=0 and < 256.

public int getItem(int x, int y) {
  if ((x < 0 && x > 255) || (y < 0 && y > 255)) {
    return -1; // Or you can throw an exception such as InvalidParameterException
  }
  return myArray[x, y];
}

错误的边界检查起着重要的作用这一点。

Error bounds checking plays an important role for this.

我会重新考虑你的努力做的,这样的事情是不可读的,什么是你想达到什么目的?也许你可以使用不同的收藏

I would rethink what your trying to do, something like this is unreadable, what are you trying to achieve? Perhaps you can use a different collections?

修改

改变了类型,因为你改变了code。

Changed the types since you changed the code.

这篇关于二维数组在Java中,通过人物索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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