[英]Is this returning an empty list?
我有一种从列表中删除元素的方法,
List<LinkedList<Object>> list = new LinkedList<>();
删除两个元素,返回一个列表,然后将其放入队列中。names = queue.removePair();
public List removePair() {
List<E> nList = new LinkedList<>();
if (list.isEmpty() == true) {
throw new InsufficientElementsException();
}
if (list.isEmpty() == false) {
Object temp;
for (int i = 0; i < list.size(); i++) {
temp = list.get(i).size();
if (temp.equals(2)) {
nList.add((E) list.get(i));
list.remove(i);
}
}
return nList;
}
return nList;
}
我相信这是行不通的,因为当我返回Nlist时,它只返回第一行中声明的那个吗? 我该如何解决?
您正在使用索引同时从列表中remove
和get
元素。 remove
,您的索引将是错误的。 在for循环中使用Iterator
代替:
for (Iterator<List<Object>> iterator = list.iterator(); iterator.hasNext();) {
List<Object> l = iterator.next();
if (l.size() == 2) {
nList.add((E) l);
iterator.remove();
}
}
您的以下代码:
if (temp.equals(2))
始终返回false。 这就是为什么您总是得到空清单的原因。
我已经编写了可以解决您问题的代码。 尝试一下。注释中提到了更改。
// Used a generic class
public class TestClass<T> where T:LinkedList<Object>
{
public List<T> list = new List<T>();
public List<T> TestMethod()
{
List<T> nList = new List<T>();
// Removed IsEmpty , used Count instead
if (list.Count == 0) {
//throw new InsufficientElementsException();
}
if (list.Count > 0) {
int temp;
for (int i = 0; i < list.Count; i++)
{
// To find out the count of nodes in a particular item of the list
temp = list.ElementAt(i).Count;
T obj = list.ElementAt(i);
if (temp == 2)
{
nList.Add(obj);
list.RemoveAt(i);
}
}
return nList;
}
return nList;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.