数组列表和使用迭代器

时间:2017-12-20 10:10:20

标签: java arrays

我试图从Java中的数组列表中删除元素,我收到错误

    public void removeBook(){
 int i=Integer.parseInt(JOptionPane.showInputDialog("Pleanse input isbn to be removed"));
        Iterator b=books.iterator();
        while(b.hasNext()){
            if(i==((Book)b).ISBN)b.remove();
        }
    }

出现此错误的原因是什么?如何解决?

import tensorflow as tf 
import numpy as np 
import matplotlib.pyplot as plt 

data_path='christmas.tfrecords'

with tf.Session() as sess:
    feature={'image':tf.FixedLenFeature([],tf.string),'label':tf.FixedLenFeature([],tf.int64)}
    # Create a list of filenames and pass it to a queue
    filename_queue = tf.train.string_input_producer([data_path], num_epochs=1)
    # Define a reader and read the next record
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    # Decode the record read by the reader
    features = tf.parse_single_example(serialized_example, features=feature)
    # Convert the image data from string back to the numbers
    image = tf.decode_raw(features['image'], tf.float32)

    # Cast label data into int32
    label = tf.cast(features['label'], tf.int32)
    # Reshape image data into the original shape
    image = tf.reshape(image, [224, 224, 1])

    # Any preprocessing here ...

    # Creates batches by randomly shuffling tensors
    images, labels = tf.train.shuffle_batch([image, label], batch_size=10, capacity=30, num_threads=1, min_after_dequeue=10)

    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    sess.run(init_op)
    # Create a coordinator and run all QueueRunner objects
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    for batch_index in range(5):
        img, lbl = sess.run([images, labels])
        img = img.astype(np.uint8)
        for j in range(6):
            plt.subplot(2, 3, j+1)
            plt.imshow(img[j, ...])
            plt.title('cat' if lbl[j]==0 else 'dog')
        plt.show()
    # Stop the threads
    coord.request_stop()

    # Wait for threads to stop
    coord.join(threads)
    sess.close()

谢谢。

3 个答案:

答案 0 :(得分:1)

bIterator,不是Book。您应该致电b.next()以获取当前Book。您应该使用参数化类型 - Iterator<Book> - 以避免将当前元素强制转换为Book

public void removeBook() {
    int i=Integer.parseInt(JOptionPane.showInputDialog("Pleanse input isbn to be removed"));
    Iterator<Book> b=books.iterator();
    while(b.hasNext()) {
        if(i == b.next().ISBN)
            b.remove();
    }
}

另一个建议是,不使用直接访问ISBN属性,而是使用getter - getISBN()

答案 1 :(得分:0)

将cast b.next()类型转换为Book类型对象,如下所示,然后进行比较。实际上这种情况正在发生,因为您正在尝试将迭代器类型强制转换为预订类型

public void removeBook(){
int i=Integer.parseInt(JOptionPane.showInputDialog("Pleanse input isbn to be removed"));
        Iterator b=books.iterator();
        while(b.hasNext()){
            Book b1=(Book) b.next();
            if(i==(b1.ISBN)){
              b.remove();
            }
        }
    }

答案 2 :(得分:0)

while循环中的代码不是很清楚,只需将Iterator对象强制转换为对象并将其删除

   Iterator itr = books.iterator();
    int i=Integer.parseInt(JOptionPane.showInputDialog("Please input isbn to be removed"));

    Book Element = "";

    while (itr.hasNext()) {
      Element = (Book) itr.next();
      if (Element.id == i) {   
        itr.remove();
        break;
      }
    }

PS:你不能将Book对象与Integer&#39; i&#39;进行比较,如果&#39; i&#39;是要删除的书的id,你必须比较Book.id == i或String书名:Element.name.equals(&#34; nameInput&#34;)