如何避免Java.util.IllegalStateException在以下code? [英] How to avoid Java.util.IllegalStateException in the following code?
问题描述
我有整的与它重复值的列表。我需要做的是找到重复的整数,增加他们的价值,然后通过移除发现重复的结果添加到列表中。下面是我在做什么:
I have a List of integer's with duplicate values in it. What I need to do is find the duplicate integers, add their value and then add the result to the list by removing the duplicates found. Here is what I am doing:
List<Integer> list1 = new ArrayList<Integer>();
list1.add(2);
list1.add(5);
list1.add(3);
list1.add(5);
list1.add(4);
List<Integer> list2 = new ArrayList<Integer>();
Iterator<Integer> it = list1.iterator();
while (it.hasNext()) {
Integer int1 = it.next();
if (list2.isEmpty()) {
list2.add(int1);
it.remove();
} else {
ListIterator<Integer> it2 = list2.listIterator();
while (it2.hasNext()) {
Integer int2 = it2.next();
if (int2 != int1) {
it2.add(int1);
it.remove();// I get exception here
} else {
it2.remove();
it.remove();
Integer newint = int1 + int2;
it2.add(newint);
}
}
}
}
for(Integer in : list2){
System.out.println(in);
}
输出应该像结果
2结果
10结果
3结果
4
感谢您的时间。
推荐答案
如果你被允许使用地图,你可以做一些简单的这样的(伪传入code):
If you are allowed to use a Map you could do something simple like this (incoming pseudocode):
create empty Map m
for each Integer x in list1 do
if m does not contain key x
m.put(x, x)
else
m.put(x, m.get(x) + x)
endif
done
您的结果是m的值(这是一个集合)。
Your result are the values of m (which is a Collection).
编辑:你说你的的LatLng整数,而不是 - 我不知道,但经纬度快速谷歌后,我会拿在下面一拍,假设你想增加你的经纬度点:
You said you have LatLng instead of Integers - I don't know LatLng but after a quick google I'd take a shot at the following, assuming that you want to "add" up your LatLng points:
create empty Map<LatLng, LatLng> m
for each LatLng x in list1 do
if not m.containsKey(x)
m.put(x, x)
else
m.put(x, LatLng.newInstance(m.get(x).getLatitude() + x.getLatitude(),
m.get(x).getLongitude() + x.getLongitude()))
endif
done
我可以在这里看到的唯一的问题是,这个 m.containsKey(X)
依赖于正确实施的等于
,这我不知道看完<一个href=\"http://gwt-google-apis.google$c$c.com/svn/javadoc/maps/1.0/com/google/gwt/maps/client/geom/LatLng.html#isEquals%28com.google.gwt.maps.client.geom.LatLng%29\"相对=nofollow>这个
The only problem I can see here is that this m.containsKey(x)
depends on the correct implementation of equals
, which I'm not sure after reading this
这篇关于如何避免Java.util.IllegalStateException在以下code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!