java数组 类型,具有多种数据类型的Java数组

What can I use to store multiple different types of data, Int/String/etc.? I come from a PHP background where I can store different types of data into an array, but I don't know how to do that in Java.

Take this example:

$array = array(

"val1" => 1,

"val2" => "cat",

"val3" => true

);

How can I make something similar in Java?

解决方案

Java is a strongly typed language. In PHP or Javascript, variables don't have a strict type. However, in Java, every object and primative has a strict type. You can store mutliple types of data in an Array, but you can only get it back as an Object.

You can have an array of Objects:

Object[] objects = new Object[3];

objects[0] = "foo";

objects[1] = 5;

Note that 5 is autoboxed into new Integer(5) which is an object wrapper around the integer 5.

However, if you want to get data out of the array, you can only get it as an Object. The following won't work:

int i1 = objects[1]; // Won't work.

Integer i2 = objects[2]; // Also won't work.

You have to get it back as an Object:

Object o = objects[0]; // Will work.

However, now you can't get back the original form. You could try a dangerous cast:

String s = (String) o;

However you don't know that o is a String.

You can check with instanceof:

String s = null;

if (o instanceof String)

s = (String) o;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值