我已经实现了一个简单的链表类,我现在想在循环中使用它。 我想知道如何在循环的每次迭代中最好地将名称分配给列表。
本质上我循环一些整数,我想只给每个列表的整数名称,但我不能说
列表i =新列表();
对 ?
可能有一种简单的方法可以做到这一点,但我不确定如何,并将感激不尽
I have implemented a simple linked list class and I would now like to use it in a loop. I am wondering how to best assign names to the list in each iteration of the loop.
Essentially I am looping over some integers, and I would like to just give each list the name of that integer, but I cannot say
List i = new List();
right ?
There probably is an easy way to do this, but I m not sure how, and would be grateful for
最满意答案
我认为你将变量的作用与集合的作用混为一谈。 根据您的问题,我收集您要为循环中的每个索引创建一个列表,并且您希望以后能够通过其索引访问该列表:
ArrayList<LinkedList<String>> listOfLists = new ArrayList<LinkedList<String>>(); for(int i = 0; i < 10; i++) { LinkedList<String> list = new LinkedList(); listOfLists.add(list); // do stuff to the list... } // access LinkedList<String> thirdList = listOfLists.get(2); // index 2 = third entry所以你看,LinkedLists没有根据i的值命名 ,但你仍然可以通过给定的i值来访问它们。
I think you're confusing the role of variables with the role of collections. From your question I gather that you want to create a list for each index in your loop, and you would like to later be able to access that list by its index:
ArrayList<LinkedList<String>> listOfLists = new ArrayList<LinkedList<String>>(); for(int i = 0; i < 10; i++) { LinkedList<String> list = new LinkedList(); listOfLists.add(list); // do stuff to the list... } // access LinkedList<String> thirdList = listOfLists.get(2); // index 2 = third entrySo you see, the LinkedLists are not named according to the value of i, but you can still access them by a given value of i.
更多推荐
发布评论