我怎样才能切一个ArrayList了在Java中ArrayList的? [英] How can I slice an ArrayList out of an ArrayList in Java?

查看:1202
本文介绍了我怎样才能切一个ArrayList了在Java中ArrayList的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得的ArrayList Java中的数组切片?具体来说,我想要做这样的事情:

How do I get an array slice of an ArrayList in Java? Specifically I want to do something like this:

ArrayList<Integer> inputA = input.subList(0, input.size()/2);
// where 'input' is a prepouplated ArrayList<Integer>

所以,我预计今年的工作,但Java的返回列表 - 所以它是不兼容的。当我尝试投它,Java将不会放过我的。我需要一个的ArrayList - ?我该怎么办

So I expected this to work, but Java returns a List - so it's incompatible. And when I try to cast it, Java won't let me. I need an ArrayList - what can I do?

推荐答案

在Java中,它使用的接口类型,而不是具体的类中的API很好的做法。

In Java, it is good practice to use interface types rather than concrete classes in APIs.

您的问题是,你正在使用的ArrayList (可能在很多地方),你真的应该使用列表。因此,您创建了自己的问题,造成不必要的限制,该清单是的ArrayList

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

这是您的code应该是什么样子:

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);


您提出的解决方案,问题是/是这样的:


Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

这是通过使子表的副本的作品。它是不是在正常意义上的切片。此外,如果子列表大,则使得副本将是昂贵的。

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.

这篇关于我怎样才能切一个ArrayList了在Java中ArrayList的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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