编程对我来说是新的,我试图了解一些概念。我正在尝试制作一个简单的小程序,在地图上显示欧洲的首都城市,并使用drawLine方法将它们连接起来。我遇到了一个问题,我无法成功加入两个省会城市。我想我理解为什么,但我想不出办法绕过它。 draw方法中的后两个参数与前两个参数相同,但我无法跳过第一次迭代。这对我来说是全新的,我现在正试图从书本和网络中学习。
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image, 0, 0, this);
for (Entry<String, co> entry : map.entrySet())
{
g.setColor(Color.BLUE);
g.fillOval(entry.getValue().a, entry.getValue().b, 5, 5);
g.setColor(Color.BLUE);
g.drawString(entry.getKey(), entry.getValue().a+7, entry.getValue().b+7);
g.setColor(Color.RED);
g.drawLine(entry.getValue().a, entry.getValue().b, 0, 0);//Problem
}
}
有人可以把我推向正确的方向吗?我正在考虑使用迭代器而不是每个循环使用迭代器,这是我目前唯一的想法。
答案 0 :(得分:7)
你可以:
例如:
map.entrySet().skip(1).forEach(...);
答案 1 :(得分:7)
可能不优雅,但它会起作用,不会产生任何明显的性能影响:
boolean isFirst = true;
for(...) {
if(!isFirst) {
// your code
} else {
isFirst = false;
}
}
答案 2 :(得分:3)
以下是两个基本选项:
a)您可以使用“for each”循环并设置临时布尔来帮助。
// set a boolean outside the loop that we query and update inside it
boolean firstRun = true;
for (Object obj : someList) {
if (firstRun) {
firstRun = false;
doFirstIterationOnly();
continue;
}
doExceptOnFirstIteration();
}
b)“for i”循环,从第二个元素开始,完全忽略第一个元素。
// start 'i' on index 1 instead of the usual index 0
for (int i=1; i < collection.size(); i++) {
Element neverFirst = collection.get(i);
doSkippingFirstElement();
}
答案 3 :(得分:3)
最好使用Iterator
:
final Map<String, String> map = new HashMap<>();
final Iterator<Entry<String, String>> iter = map.entrySet().iterator();
if (!iter.hasNext()) {
//map is empty - handle
}
iter.next();
while (iter.hasNext()) {
final Entry<String, String> e = iter.next();
//your code
}
我更喜欢boolean
方法,因为您不需要在每次迭代中检查标志。只要在消耗每个额外项目之前重新检查hasNext()
,此方法还允许在每次迭代中使用多个条目的自由度。
P.S。
请坚持Java naming conventions。您的class co
应该在PascalCase
。另外Co
可能不是class
的最佳名称 - 尝试为从类到变量的所有内容选择有意义的名称。