Java 使用带HashSet的迭代器类的NoTouchElementException

Java 使用带HashSet的迭代器类的NoTouchElementException,java,android,Java,Android,我不明白为什么这段代码会给我一个NoTouchElementException 基本上,我所做的是遍历Gatt服务器的HashSet,如果它们的设备地址匹配,则关闭它们与设备的连接 BluetoothDevice device = mDeselectedDeviceData.device; Iterator<BluetoothGatt> it = BleManager.getInstance().myGattConnections.iterator(); while (it.hasN

我不明白为什么这段代码会给我一个
NoTouchElementException

基本上,我所做的是遍历
Gatt
服务器的
HashSet
,如果它们的设备地址匹配,则关闭它们与设备的连接

BluetoothDevice device = mDeselectedDeviceData.device;
Iterator<BluetoothGatt> it = BleManager.getInstance().myGattConnections.iterator();
while (it.hasNext()) {
    if(it.next().getDevice().getAddress() == device.getAddress()){ 
        it.next().close();
    }
}
正在抛出错误

>NoSuchElementException
但是,如果我记录它,
it.hasNext()
has是真的

while (it.hasNext()) {
    Log.(TAG,"it.hasNext() is "+String.valueOf(it.hasNext())); // Prints true
    if(it.next().getDevice().getAddress() == device.getAddress()){ 
        it.next().close();
    }
}
在这里调用
it.next()
两次,迭代器前进两个位置。我很确定你的意思是

BluetoothGatt gatt = it.next();
if(gatt.getDevice().getAddress() == device.getAddress()){ 
    gatt.close();
}

是的,没错,谢谢你。但是现在如果只有一个GATT服务器,我无法进行比较,因为
it.next()
为false。难道没有像it.current()这样的方法吗?对不起,我问了个愚蠢的问题。不,没有。只能使用
.next()
提取元素,如果要多次使用,必须将其存储在变量中。好的,我想我找到了。如果集合中只有一个元素,它.next()将在第一次调用时返回集合中的第一个元素。谢谢。可能有两份
if(it.next().getDevice().getAddress() == device.getAddress()){ 
    it.next().close();
}
BluetoothGatt gatt = it.next();
if(gatt.getDevice().getAddress() == device.getAddress()){ 
    gatt.close();
}