Java 2D ArrayList 和排序
我需要按商品所在的过道对购物清单进行排序,例如:
[面包] [1]
[牛奶] [2]
[Cereal] [3]
我打算用 ArrayList 来做这件事,并且想知道如何制作 2D ArrayList 额外问题:关于如何按过道编号排序有什么想法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你没有一个类来保存你的物品+过道信息吗?例如:
如果您不这样做,请考虑制作一个 - 这绝对是一种比尝试将这些属性粘贴到另一个 ArrayList 中的 ArrayList 更好的方法。一旦你确实有了这个类,你要么需要编写一个 比较器为您的对象或创建“项目”Comparable 本身:
那么你所要做的就是调用排序:
Don't you have a class that holds your item + aisle information? Something like:
If you don't, consider making one - it's definitely a better approach than trying to stick those attributes into ArrayList within another ArrayList. Once you do have said class, you'll either need to write a Comparator for your objects or make 'Item' Comparable by itself:
Then all you do is invoke sort:
如果要对 ArrayList 的 ArrayList 进行排序,则可以使用 ColumnComparator。
如果您想对自定义对象的 ArrayList 进行排序,则可以使用 BeanComparator 。
If you want to sort an ArrayList of ArrayLists then you can use the ColumnComparator.
If you want to sort an ArrayList of your custom Object then you can use the BeanComparator.
我知道这个问题很久以前就被问过,但实际上我也遇到了同样的问题。如果您不知道列表中会有多少变量,但这不是一个大数字,您可以为每个选择实现比较器。例如,
我有 ArrayList> 并希望按列对其进行排序,并且我知道嵌套列表由可变数量的对象组成,我可以为每个可能的值实现比较器:
}
并且这样调用:
在每个比较器中只需修改
.get(x)
其中 x 是您想要排序的列数。可以使用 boolean isNumeric(String str); 函数,因为您无法在一个列表上存储不同类型的对象,因此我将对此的识别放入比较器并将 String 解析为任何其他类型。
请记住,这个
比较器
及其“计算”会被算法进行的每次比较调用,因此效率极低......尽管如此,这仍然是一种解决方案。
I know the question was asked long ago but actually i had the same problem. If you dont know how many variables you would have on list but this is not a big number you could just implement comparator for every choose. eg
I have
ArrayList<ArrayList<Object>>
and want to sort it by column's and i know that the nested list consist of variable number of objects i can just implement comparator for every possible value:}
And call this this way:
In every comparator just modifying
.get(x)
where x is number of collumn by which you want sort.The
boolean isNumeric(String str);
function may be used because you cant store different type of objects on one list so I put the recognition of this to the comparator and parse String to any other type.Remember that this
comparator
and its "calculations" are called to every single comparison made by algorithm so it is extremely inefficient...Despite this fact this is kind of sollution.