简体   繁体   English

大小未知时的java 2d数组

[英]java 2d array when size is not known

I need to create and order an array of objects, problem is the objects cannot be ordered by themselves. 我需要创建和排序一个对象数组,问题是对象不能自己排序。 Instead they are ordered based off an integer value. 相反,它们是基于整数值排序的。 So I thought of using a 2d array. 所以我想到了使用2d数组。

 Object[][] array = new Object[][]

That way I can store in the array the 这样我就可以存储在数组中了

 [integer to order the objects][object]

But the problem is I don't know how many objects there will be that need to be ordered, so, do I need to use an Arraylist instead? 但问题是我不知道需要订购多少个对象,所以,我需要使用Arraylist吗?

Either way, is it possible to use a collection.sort command, and how can I possible get an array to behave as described? 无论哪种方式,是否可以使用collection.sort命令,我怎样才能使数组的行为如上所述?

Thanks 谢谢

You need to forget about raw arrays and start thinking in terms of the Java Collections Framework. 您需要忘记原始数组并开始考虑Java Collections Framework。

For sorting use a TreeMap<Integer, Object> . 对于排序使用TreeMap<Integer, Object> After you've put all your objects in, you can use values() to get the objects in proper order. put所有对象后,可以使用values()以正确的顺序获取对象。

Using the map you have also eliminated all problems of size determination. 使用地图,您还消除了尺寸确定的所有问题。

Use ArrayList with Comparator interface to order them. 使用带有Comparator interface ArrayList对它们进行排序。

Moreover TreeMap is a Sorted Map which will sort your Object on the basis of Integer value as you mention them as the Key to the Values. 此外, TreeMap是一个Sorted Map ,它会根据Integer值对您的Object进行排序,因为您将它们称为值的键。

TreeMap<Integer, Object>

Integer - Key

Object  - Value

You don't need to initialize the Collections like u need to do with Arrays.... So thats another probs taken care off.... 不需要像你需要用数组那样初始化集合 ......所以那是另一个probs照顾....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM