是否有一种“正确”的方式将字符串和整数存储在 Java 中的同一个数组中?

我认为在 Java 中将 String 和 Integer 存储在同一个数组中会更有效,但我知道 Java 是强类型的。

有没有办法做到这一点?,如果没有,我该怎么办?


哈士奇WWW
浏览 202回答 3
3回答

噜噜哒

您可以使用 anObject[]来执行此操作。但请不要。如果你觉得你需要在一个数组中混合不同的类型,也许是时候重新考虑你的设计了(这里有一个想法:在存储之前将 s 转换为 s 甚至 s String)Integer。int将这些不同的数据类型存储在同一个数组中根本是不“正确的”。

呼啦一阵风

定义“更高效”通常意味着更少的存储空间或更少的处理器密集型。这些是截然相反的目标。挑战在于平衡它们。您可以使用Object[]前面所述的类型,但这需要确定类型,然后将每个元素转换为 aString或Int在使用之前。装箱、转换为Object类型和拆箱、转换为原始类型在 Java 中是相对昂贵的操作。如果必须使用相同的数组索引存储它们,可能的解决方案:如果不需要对int项做进一步的数学处理,使用.toString()方法将其转换为a String,并存储在s的数组中String。如果 Integer 元素的数量会比Strings 少很多,使用.toString()方法将其转换为 aString并将其存储在 s 的数组中String。然后使用.(被认为是一个缓慢的操作)将 s 解析int出来Integer.parseInt()parseInt()如果内存不是问题,请创建两个大小相同的单独数组,一个是 type String,另一个是 type int。选择一个作为主要(人口最多)。使用标志值(“” forString和Integer.MIN_VALUEfor int)来指示结果是其他类型,并且应该使用存储在其他数组中的值。这以使用更多内存为代价保留了公共索引。如果可能,我建议重写代码以使用两个单独的数组。

慕尼黑的夜晚无繁华

&nbsp; package ArrayPractice;&nbsp; &nbsp; import java.util.ArrayList;&nbsp; &nbsp; import java.util.Scanner;&nbsp; &nbsp; public class Question8 {&nbsp; &nbsp; &nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter the array range: ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int i= sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int [] data= new int[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ArrayList<Object> testing= new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object [] demo= new Object[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int y = 0; y < data.length; y++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter the Array number: " + y);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; demo[y]= sc.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(Object o: demo){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(o);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java