Java 以随机方式访问列表列表

Java 以随机方式访问列表列表,java,Java,我试图创建一个列表列表,并根据需要填充它们,但我得到了数组越界异常。我的代码是: List<List<String>> seperatedData = new ArrayList<List<String>>(); int index; while ((line = br.readLine()) != null) { String[] data = line.split(","); index = data[0].hashCode(

我试图创建一个列表列表,并根据需要填充它们,但我得到了数组越界异常。我的代码是:

List<List<String>> seperatedData = new ArrayList<List<String>>();
int index;

while ((line = br.readLine()) != null) {
    String[] data = line.split(",");
    index = data[0].hashCode() % redCount;

    if(seperatedData.get(index) == null) {
            List<String> single = new ArrayList<String>();
            seperatedData.add(single);
            seperatedData.get(index).add(line);
    } else {
            seperatedData.get(index).add(line);
    }
}
List separateddata=new ArrayList();
整数指数;
而((line=br.readLine())!=null){
String[]data=line.split(“,”);
索引=数据[0]。hashCode()%redCount;
if(separateddata.get(index)==null){
List single=new ArrayList();
单独数据添加(单个);
单独的数据。获取(索引)。添加(行);
}否则{
单独的数据。获取(索引)。添加(行);
}
}

变量
separateddata
是一个空的
列表
。因此,第一次执行
时,如果执行(separateddata.get(index)=null)
,您将获得一个
索引自动边界异常
,无论
索引的值如何

您都不能通过以下方式使用
列表
: 假设您有一个包含
5
元素的列表,并尝试向索引
10
添加一些内容。它是
null
,因此您可以创建新的子列表并将其添加到集合中。然而,它不会被添加到第十位,但它将在下一个索引中被访问(在这种情况下,它将增加5,总共6项)

所以下面的代码是错误的

        seperatedData.add(single);
        seperatedData.get(index).add(line);
要修复它,请使用地图

Map<Integer,List<String>> seperatedData = new HashMap<>();
Map separateddata=newhashmap();
并使用它:

if(seperatedData.get(index) == null) {
            List<String> single = new ArrayList<String>();
            seperatedData.put(single);
            seperatedData.get(index).add(line);
    } else {
            seperatedData.get(index).add(line);
    }
if(separateddata.get(index)==null){
List single=new ArrayList();
单独数据输入(单个);
单独的数据。获取(索引)。添加(行);
}否则{
单独的数据。获取(索引)。添加(行);
}

现在它应该可以正常工作了

如果我发现了这个异常并创建了一个新的列表,我如何准确地将其填入正确的位置?假设我的
索引第一次是3,我如何使
单独的数据包含
{null,null,null,data}
?这不是
数组列表的工作方式。你知道不同索引的确切数目吗?如果是这样,您可以使用一个基本的
List
数组,比如
List[]separateddata=newlist[可能的索引数]
。如果确实要使用
List
执行一个for循环,将“足够高”的条目数设置为null:
separateddata.add(null)