1

Overview

I have an arrayList that holds multiple int arrays that have two parameters, key and value. (I know there exists a map library, but for this task I wish to use an arrayList).

Imagine my arrayList has the following arrays:

[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.

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.

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.

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).

Community
  • 1
  • 1
Jay Rainey
  • 386
  • 6
  • 22

6 Answers6

2

It may be more elegant to produce a class to hold your two values and ensure that implements Comparable, as shown below:

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.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
2

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. 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 Comparators.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
1

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.

If you chose this option, after adding the element all you need to do is to call .sort() on your List.

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

Community
  • 1
  • 1
bjedrzejewski
  • 2,378
  • 2
  • 25
  • 46
0

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

INSERTED ELEMENT

2

3

*/

Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165
0

There is also a version of add that takes the index at which to add the new item.

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)
robertjlooby
  • 7,160
  • 2
  • 33
  • 45
0

Use a Comparator of int[] along with 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];
        }
    }
}
restricteur
  • 302
  • 5
  • 17