在Java中使用列表 [英] Cons'ing a List in Java

查看:118
本文介绍了在Java中使用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个 java.util.List列表,我想创建一个新的列表元素列表的开头(即,我想要 cons e list )。例如,如果 list

Say I have a java.util.List list and I want to create a new List by adding an element e to the beginning of list (i.e., I want to cons e and list). For example, if list is

[1,2,3,4]

e $ c> 5 ,则 cons(e,list)将为

and e is 5, then cons(e,list) will be

[5,1,2,3,4]

对于 list cons(e,list)的元素进行共享,但

It's OK for the elements of list and cons(e,list) to be shared, but list should not be modified.

实现 cons的最简单和/或最有效的方法是$ $ c>?结果是不可修改的。

What is the simplest and/or most efficient way to implement cons? It's OK for the result to be unmodifiable. Use of the Google Collections Library is allowed.

如果列表 com,则应如何使用Google Collections Library。 google.common.collect.ImmutableList

推荐答案

public static<T> List<T> cons(List<T> list, T t) {
    ArrayList<T> result = new ArrayList<T>(list);
    result.add(0, t);
    return result;
}

编辑以响应注释:
由于问题最简单和/或最有效的方式来实现缺点,我用最简单。我不会感到惊讶,学习有更有效的方法。将元素放在列表之前是另一个有效的方法,并且最初分配正确的大小可能会提高性能。过早的优化是所有邪恶的根源。

Edited in response to comments: Since the question asked for "the simplest and/or most efficient way to implement cons," I went with "simplest". I wouldn't be surprised to learn there are more efficient ways. Putting the element in before the list is another valid approach, and allocating the correct size initially could probably improve performance. Premature optimization is the root of all evil.

这篇关于在Java中使用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆