Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Language agnostic 插入列表的优雅方式_Language Agnostic - Fatal编程技术网

Language agnostic 插入列表的优雅方式

Language agnostic 插入列表的优雅方式,language-agnostic,Language Agnostic,因此,我有一个对象列表,我想更新符合某些条件的项,如果没有匹配的项,则插入一个对象。我提出的代码看起来并不优雅,它是这样的: def upsert(type, text) messages.each do |message| if message.type == type message.text = text end end unless messages.any?{|message| message.type == type} message

因此,我有一个对象列表,我想更新符合某些条件的项,如果没有匹配的项,则插入一个对象。我提出的代码看起来并不优雅,它是这样的:

def upsert(type, text)
  messages.each do |message|
    if message.type == type
      message.text = text
    end
  end

  unless messages.any?{|message| message.type == type}
    messages.insert(Message.new(type, text))
  end
end

这取决于清单本身的执行情况。如果可以使用每个元素的唯一哈希实现列表,那么获取一个元素可能非常简单

因此,它可以归结为列表本身的实现。如果它是一种随机访问列表,随着时间的推移获取常量,那么这个操作将很简单。如果列表是纯顺序访问列表,则此选项与您的实现相同

例如,在使用Java时,我会这样做:

假设“type”唯一标识一个元素,我将在Item类中定义和

if(list.contains(item))
{
    Item item = list.get(list.indexOf(item));
    item.setText(text);
}
else
{
    list.add(item);
}
如果类型不是唯一的,则仍然可以实现。底线是清单的实施。有了一个好的随机访问列表,事情几乎总是简单的:

if(!list.contains(item))
{
    return;
}
do
{
    int i = list.indexOf(item);
    Item item = list.get(i);
    item.setText(text);
    list = list.subList(i+1, list.size());
} while(list.indexOf(item) != list.lastIndexOf(item));

不,类型不能唯一标识一个元素,因此可以更新多个项。在这种情况下,您需要一种更优雅的方法。您仍然可以使用散列和随机访问列表。底线不变:取决于列表的类型。请参阅我的最新答案。