简体   繁体   English

将数组插入int数组的arraylist的正确位置

[英]Insert array into correct location of arraylist of int arrays

Overview 总览

I have an arrayList that holds multiple int arrays that have two parameters, key and value. 我有一个arrayList,它包含多个具有两个参数,键和值的int数组。 (I know there exists a map library, but for this task I wish to use an arrayList). (我知道有一个地图库,但是对于此任务,我希望使用arrayList)。

Imagine my arrayList has the following arrays: 想象一下我的arrayList具有以下数组:

[3, 99][6, 35][8, 9][20, 4][22, 13][34, 10] [3,99] [6,35] [8,9] [20,4] [22,13] [34,10]

As you can see, they are in order by the index, which is done when I first add them to the arrayList. 如您所见,它们按索引顺序排列,这是在我第一次将它们添加到arrayList时完成的。

My problem 我的问题

if I want to add an array to this arrayList it would appended to the end of the list, whereas I want to add it to the correct position in the list. 如果我想向此arrayList添加一个数组,它将添加到列表的末尾,而我想将其添加到列表中的正确位置。

I'm fairly new to arrayLists, and as such was wondering if there exists an elegant solution to this problem that I have not come across. 我对arrayLists还是相当陌生,因此想知道是否存在一个我没有遇到过的优雅解决方案。

Current thoughts 目前的想法

Currently, my solution would be to iterate over the arrayList, then for every array temporally store the key (array[0]), I would then iterate over again and add my array in the correct position (where it's key is in-between two other keys). 当前,我的解决方案是遍历arrayList,然后为每个临时存储键的数组(array [0]),然后我再次遍历并将数组添加到正确的位置(键在两个之间)其他键)。

It may be more elegant to produce a class to hold your two values and ensure that implements Comparable , as shown below: 产生一个类来容纳您的两个值并确保实现Comparable可能更优雅,如下所示:

public class Foo implements Comparable<Foo> {

  private int x; // your left value
  private int y; // your right value

  // Constructor and setters/getters omitted

  public int compareTo(Foo o) {
    return Integer.compare(x, o.getX());
  }
}

Then add and sort as follows: 然后添加并排序如下:

List<Foo> listOfFoos = new ArrayList<Foo>;
// ...
listOfFoos.add(new Foo(33,55));
Collections.sort(listOfFoos);   

That would be the most readable solution. 那将是最易读的解决方案。 There may be faster options, but only optimise if you can prove this part is a bottleneck. 可能会有更快的选项,但是只有在您可以证明这部分是瓶颈的情况下,才进行优化。

Your idea of iterating through is correct; 您的迭代想法是正确的; however there is no need to perform the iteration twice. 但是,无需执行两次迭代。 Finding the right index and inserting the element can be done in one loop. 查找正确的索引并插入元素可以在一个循环中完成。 ArrayList has a method add(int, E) that can insert an element into any position in the list. ArrayList具有方法add(int, E) ,可以将元素插入列表中的任何位置。 Try this: 尝试这个:

//the value you want to insert
int[] toInsert = {someValue, someOtherValue};

//assume theList is the list you're working with
for(int index = 0; index < theList.size() -1; index ++)
{
     int key = theList.get(index)[0];
     int nextKey = theList.get(index + 1)[0];

     //if we've reached the correct location in the list
     if (toInsert[0] > key && toInsert[0] < nextKey)
     {
          //insert the new element right after the last one that was less than it
          theList.add(index + 1,toInsert);
     }
}

Note that this method assumes that the list is sorted to begin with. 请注意,此方法假定列表从头开始排序。 If you want to make that a guarantee, look into some of the other answers describing sorting and Comparator s. 如果要保证这一点,请查看其他一些描述sorting和Comparator的答案。

First Option 第一选择

If you want to be able to sort your array you should be storing Comparable Objects. 如果希望能够对数组进行排序,则应该存储可比较对象。

So, you can create a Class that will hold your two value array and implement the Comparable interface. 因此,您可以创建一个类,该类将保存您的两个值数组并实现Comparable接口。

If you chose this option, after adding the element all you need to do is to call .sort() on your List . 如果选择此选项,则添加元素后,只需在List上调用.sort()

Second Option 第二选择

You can define Comparator that you can use for sorting. 您可以定义比较 ,您可以使用排序。 This would be reusable and would allow you to keep your two dimensional arrays. 这将是可重用的,并将允许您保留二维数组。 You will also have to sort after each time you add. 每次添加后,您还必须进行排序。

Third Option 第三选择

You could define your Comparator on the fly as shown in this particular question: Java Comparator class to sort arrays 您可以按以下特定问题所示动态定义Comparator: Java Comparator类对数组进行排序

you can do the following: 您可以执行以下操作:

import java.util.ArrayList;

   public class AddElementToSpecifiedIndexArrayListExample {

  public static void main(String[] args) {
//create an ArrayList object
  ArrayList arrayList = new ArrayList();

//Add elements to Arraylist
   arrayList.add("1");
   arrayList.add("2");
   arrayList.add("3");

/*
  To add an element at the specified index of ArrayList use
  void add(int index, Object obj) method.
  This method inserts the specified element at the specified index in the
  ArrayList.  
*/
arrayList.add(1,"INSERTED ELEMENT");



System.out.println("ArrayList contains...");
for(int index=0; index < arrayList.size(); index++)
  System.out.println(arrayList.get(index));

    }
}

/* Output would be ArrayList contains... 1 / *输出将为ArrayList包含... 1

INSERTED ELEMENT 插入元素

2 2

3 3

*/ * /

There is also a version of add that takes the index at which to add the new item. 还有一个add版本,该版本采用add新项目的索引。

int i;
for(i=0; i<arr.size(); i++){
    if(arr.get(i)[0] >= newArr[0]){
        arr.add(i, newArr);
    }
}
if(i == arr.size())
    arr.add(i, newArr)

Use a Comparator of int[] along with binarySearch : 将int []的比较器与binarySearch一起使用:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main
{

    public static void main(String[] argv)
    {
        ArrayList<int[]> list = new ArrayList<int[]>();

        list.add(new int[] { 3, 99 });
        list.add(new int[] { 6, 35 });
        list.add(new int[] { 8, 9 });
        list.add(new int[] { 20, 4 });
        list.add(new int[] { 22, 13 });
        list.add(new int[] { 34, 10 });

        Compar compar = new Compar();

        addElement(list, new int[] { 15, 100 }, compar);


        for(int[] t : list)
        {
            System.out.println(t[0]+" "+t[1]);
        }

    }

    private static void addElement(ArrayList<int[]> list, int[] elem, Compar compar)
    {
        int index = Collections.binarySearch(list, elem, compar);

        if (index >= 0)
        {
            list.add(index, elem);
            return;
        }

        list.add(-index - 1, elem);
    }

    static class Compar implements Comparator<int[]>
    {
        @Override
        public int compare(int[] a, int[] b)
        {
            return a[0] - b[0];
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM