add a variable into an array in a specific position - java

I'm trying to add a string into my array in the 3rd position because I need to do so for a loop I'm executing after it.
ArrayList<String> namesArray = new ArrayList<>();
namesArray.add(3, mString);
It gives an out of bonds expection, is this not possible to do?
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 0

When you say
arrayList.add(n, value);
the result is that after the add, arrayList.get(n) will have that value. You're trying to arrange things so that arrayList.get(3) will be mString. However, an ArrayList must be a list of consecutive elements; it can't be a "sparse array". That is, for arrayList.get(3) to exist, arrayList.get(0), arrayList.get(1), and arrayList.get(2) must also exist.
I don't know what you want those values to be (maybe null?), but you do have to set them. Java's ArrayList doesn't have an add method that automatically fills in the gap with a default value. You can add 3 nulls to the array like this:
arrayList.addAll(Arrays.asList(new String[3]));

You should fill the array with empty string before index 3 like this:
namesArray.add("");
namesArray.add("");
namesArray.add("");
Then you won't get that exception

Related

Getting IndexOutOfBoundsException in ArrayList while using .add(index, element)

I am using the list.add(index, element) function to insert elements into an ArrayList, where the index is not in order.
For eg,
first i call list.add(5, element5)
and then list.add(3, element3)
I am getting the exception java.lang.IndexOutOfBoundsException: Invalid index 5, size is 0 exception.
Please tell where I am doing wrong and how can I fix this.
You cannot add elements to indexes which do not yet exist. In general, as Japhei said, you can only add elements to indexes smaller or equal to the array length. This means, if your ArrayList is still empty, you can only add elements at index 0 or without specifying the index (which will just add it to the end).
What you want to do is initialize your ArrayList with empty elements. I normally use meaningless values like 0 or -1 for integers or empty strings depending on the array type (or null elements), and just fill them later.
But if you know how many elements you have, or what array size you need, why not just use a normal array? That would be the right way to do it.
The problem is that your ArrayList is empty and therefore the insert (via add(int index, E element) fails.
Consider using the add(E element) (documentation) to add the element to the end of the list.
You can only use indexes that are existing or one larger than the last existing. Otherwise you would have some spots with no element in it.
If you need a ficxed length to store elements on a specified position, try to fill the List before with empty entries or use an array:
MyElement[] myArray = new MyElement[theLengthOfMyArray];
myArray[5] = elementXY;
Or fill a List with null elements (shown here):
List<MyElement> myList = new ArrayList<>();
for (int i = 0; i < theTargetLengthOfMyList; i++) {
myList.add(null);
}
myList.set(5, elementXY);
So what is probably happening is, that you defined a size for your list on creating said list. According to your error message this would be 0. And on a list with the size 0, you can't set the 5th or 3rd position to anything, as they don't exist. If you would add the line where you define the variable "list", we could help you further!
You can't add to index not in list range:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
See java doc:
https://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-int-E-

Trouble putting only unique values into an array

So I have a list of countries that I am reading from a text file and some of the countries are on there more than once. I need to put each country name into a string array without any doubles, or countries put on there twice. I tried using a for loop but could not wrap my head around the logic required for this.
Thanks in advance.
Try using a Set. A Set can contain one and not more than one of a particular instance (instance1.equals(instance2) will not be true).
Instantiate a Set like so:
Set<String> s = new HashSet<String>();
Then use a for loop to add the values.
String[] countries = {"JP", "US", "CN", "RU", "RU"}; //just make pretend these were read from a file.
for (String countryName: countries){
s.add(countryName); // RU will only be added once
}
System.out.println(s);
Outputs: [JP, US, RU, CN]
There are three different ways I can see this working:
Use a Set. This is the most efficient and easiest, and uses code that works
Each time you read in an element, iterate through the array, and see if the array already contains the element. If it does, don't add it. If you can't use Sets, this is the easiest code to write.
Read in all of the elements, sort the array. Iterate through the array, and if the current element doesn't equal the previous element, then add it to a new array. This is more efficient than #2 (O(nlog(n)) vs O(n^2)), but will require more code.
In order to check to see if a country is in the array, use an if statement. As you read in each country this checks to see if if exists in the array. If it doesn't, it adds the country to the array.
if(!Arrays.asList(yourArr).contains(country)){
yourArr[i] = country;
}

How to increase the size of an arraylist

I'm trying to increase the size of an array list but it doesnt seem to want to work.
I am doing this:
final int QUEUE_CAPACITY = 27;
ArrayList adjacencyList = new ArrayList<Integer>(QUEUE_CAPACITY);
But when I try to add something with the add that has two paramters, (index,value) I get this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
You have established the initial capacity of the ArrayList, but there are still no items in the list. You can't insert an item before index 1 if it doesn't exist yet.
You must use the one-argument add method to append to the end of the list, or supply 0 as the index in the two-argument add method, so that there is something in the list.
Well, If you really want to do this.
You need to Intialise the Array with 'Integers' like '0' or so
and then instead of add() method use the set(int index, E element) method which Replaces the element at the specified position in this list with the specified element.
Any index at which you see '0' is equivalent to empty.
Are you calling the equivalent of adjacencyList.add(1, 1)? If so, you're trying to add to an empty list at index 1, which doesn't exist. Just call adjacencyList.add(<value>).
Also, include the generic type at initialization:
ArrayList<Integer> adjacencyList = new ArrayList<Integer>(QUEUE_CAPACITY);
PS. You don't usually need to adjust the initial capacity of an ArrayList unless you know the list will rarely end up being small.
That's not how it works.
If you're going to insert something at a certain position, you need to have elements stored up to the point in the list already.

Adding elements into ArrayList at position larger than the current size

Currently I'm using an ArrayList to store a list of elements, whereby I will need to insert new elements at specific positions. There is a need for me to enter elements at a position larger than the current size. For e.g:
ArrayList<String> arr = new ArrayList<String>();
arr.add(3,"hi");
Now I already know there will be an OutOfBoundsException. Is there another way or another object where I can do this while still keeping the order? This is because I have methods that finds elements based on their index. For e.g.:
ArrayList<String> arr = new ArrayList<String>();
arr.add("hi");
arr.add(0,"hello");
I would expect to find "hi" at index 1 instead of index 0 now.
So in summary, short of manually inserting null into the elements in-between, is there any way to satisfy these two requirements:
Insert elements into position larger than current size
Push existing elements to the right when I insert elements in the middle of the list
I've looked at Java ArrayList add item outside current size, as well as HashMap, but HashMap doesn't satisfy my second criteria. Any help would be greatly appreciated.
P.S. Performance is not really an issue right now.
UPDATE: There have been some questions on why I have these particular requirements, it is because I'm working on operational transformation, where I'm inserting a set of operations into, say, my list (a math formula). Each operation contains a string. As I insert/delete strings into my list, I will dynamically update the unapplied operations (if necessary) through the tracking of each operation that has already been applied. My current solution now is to use a subclass of ArrayList and override some of the methods. I would certainly like to know if there is a more elegant way of doing so though.
Your requirements are contradictory:
... I will need to insert new elements at specific positions.
There is a need for me to enter elements at a position larger than the current size.
These imply that positions are stable; i.e. that an element at a given position remains at that position.
I would expect to find "hi" at index 1 instead of index 0 now.
This states that positions are not stable under some circumstances.
You really need to make up your mind which alternative you need.
If you must have stable positions, use a TreeMap or HashMap. (A TreeMap allows you to iterate the keys in order, but at the cost of more expensive insertion and lookup ... for a large collection.) If necessary, use a "position" key type that allows you to "always" generate a new key that goes between any existing pair of keys.
If you don't have to have stable positions, use an ArrayList, and deal with the case where you have to insert beyond the end position using append.
I fail to see how it is sensible for positions to be stable if you insert beyond the end, and allow instability if you insert in the middle. (Besides, the latter is going to make the former unstable eventually ...)
even you can use TreeMap for maintaining order of keys.
First and foremost, I would say use Map instead of List. I guess your problem can be solved in better way if you use Map. But in any case if you really want to do this with Arraylist
ArrayList<String> a = new ArrayList<String>(); //Create empty list
a.addAll(Arrays.asList( new String[100])); // add n number of strings, actually null . here n is 100, but you will have to decide the ideal value of this, depending upon your requirement.
a.add(7,"hello");
a.add(2,"hi");
a.add(1,"hi2");
Use Vector class to solve this issue.
Vector vector = new Vector();
vector.setSize(100);
vector.set(98, "a");
When "setSize" is set to 100 then all 100 elements gets initialized with null values.
For those who are still dealing with this, you may do it like this.
Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";
List<Object> list= Arrays.asList(array);
But the thing is you need to identify the total size first, this should be just a comment but I do not have much reputation to do that.

How to delete one value from, and decrease the length of, a String array

I don't understand how to decrease the length of a String array. For example, with this code:
String[][] array = new String[5][2];
array[1][0] = "what";
array[2][0] = "is";
.....
.....
array[5][0] = "?";
How can I delete array[5][0] and get array.length to be 4, not 5?
If you want to remove the array element from the end , you can also use Arrays.copyOf() since jdk 1.6+
For example:
array = Arrays.copyOf(array, 4);
It just copy the original array 's first 4 elements to a new array , so it have the same effect as deleting the array[5]
If you want to remove an element from an specified index , you can use ArrayUtils.remove() from Apache Commons Lang 3 to do it .
/**Remove the element at index 3**/
array =ArrayUtils.remove(array, 3);
You cannot delete an item from an array.
But you can create a new array with smaller size and copy the content of the old array to the new one. Then, assign the value of the reference to the new array.
Consider using java.util.List. It has a method remove().
Using arrays for such things is very time consuming. I can suggest these solutions:
1. Use one of the data structures provided by Java libraries. I'd go with HashMap since its structure allows mapping a value to a key (HashMap ) and it does the part of adding, finding and removing items. You can also use them for multi-level hashmaps if you need more than 2 columns (HashMap ) you can look that up.
2. Use a List or ArrayList structure. Make a list that contains arrays or a special structure you create to store your data.
3. (Not recommended) Go for the manual route. If you have a fixed-length array, you can shift the rows back to remove that row, and use an index to define the last row. If you have a dynamic-length array you'll need to reconstruct it each time you remove a row.

Categories