【发布时间】:2019-03-28 03:15:30
【问题描述】:
我遇到了以下问题。我有一个 ArrayList(1) 的 ArrayLists(2)。我需要做的是,对结构进行排序,使 ArrayLists(2) 的第一个元素按升序向下排列 ArrayList(1)。澄清一下:
输入:
3, 8, 6
2, 14, 205, 44, 1
1, 3
输出:
1, 3
2, 14, 205, 44, 1
3, 8, 6
看看它是如何仅根据第一个值对行进行排序的。
现在为我定义arraylists的arraylist的方式是:
List<List<Integer>> graph = new ArrayList<List<Integer>>();
// and I add elements to it likewise
graph.get(currentIndex).add(new ArrayList<Integer>());
我使用 ArrayList 的原因是因为我读到它比 LinkedList 更节省内存,并且因为我正在构建一个图的邻接列表列表。在其中,节点的数量可以变化,或者每个节点的邻接列表的长度都可以变化。一行的第一个元素是start_node,下面是它的相邻元素。你能告诉我如何实现这种排序吗?
【问题讨论】:
-
more memory efficient- 尝试阅读LinkedList的优势,。对于邻接列表,您应该使用LinkedList。 -
您可以将List包装在一个对象中,然后实现
Comparable接口。在里面,在compareTo你可以实现你的逻辑。此外,LinkedList的缓存局部性更差,因此由于内存分配不连续,因此性能会更差。
标签: java list sorting arraylist data-structures