具有多种数据类型的Java数组 [英] Java Array with multiple data types

查看:468
本文介绍了具有多种数据类型的Java数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用什么来存储多种不同类型的数据(整数/字符串/等)?我来自PHP背景,可以将不同类型的数据存储到数组中,但是我不知道如何在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.

以这个例子为例:

$array = array(
    "val1" => 1,
    "val2" => "cat",
    "val3" => true
);

如何用Java做类似的事情?

How can I make something similar in Java?

推荐答案

Java是一种强类型语言.在PHP或Javascript中,变量没有严格的类型.但是,在Java中,每个对象和基元都有严格的类型.您可以将多种类型的数据存储在Array中,但只能将其作为对象取回.

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;

请注意,将5自动装箱到new Integer(5)中,这是围绕整数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;

但是您不知道o是字符串.

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

您可以使用instanceof进行检查:

String s = null;

if (o instanceof String)
    s = (String) o;

这篇关于具有多种数据类型的Java数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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