How to remove element from an array - java

I have an array for example:
String [][] test = {{"a","1"},
{"b","1"},
{"c","1"}};
Can anyone tell me how to remove an element from the array. For example I want to remove item "b", so that the array looks like:
{{"a","1"},
{"c","1"}}
I can't find a way of doing it. What I have found here so far is not working for me :(

You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:
Assign null to the array at the relevant position; e.g.
test[1] = null;
This leaves you with the problem of dealing with the "holes" in the array where the null values are. (In some cases this is not a problem ... but in most cases it is.)
Create a new array with the element removed; e.g.
String[][] tmp = new String[test.length - 1][];
int j = 0;
for (int i = 0; i < test.length; i++) {
if (i != indexOfItemToRemove) {
tmp[j++] = test[i];
}
}
test = tmp;
The Apache Commons ArrayUtils class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int), but the fact remains that this approach creates a new array object.
A better approach would be to use a suitable Collection type. For instance, the ArrayList type has a method that allows you to remove the element at a given position.

There is no built-in way to "remove" items from a regular Java array.
What you want to use is an ArrayList.

You could set the entry in the array to null (test[0][1] = null;). However, "removing" the item such that the array will have one element less than before is not doable without recreating the array. If you plan to change data in the data structure regularly an ArrayList (or another Collection class depending on your needs) might be more convenient.

My solution is:
You cannot remove an element from an array => it's correct, but we can do something to change current array.
No need assign null to the array at the relevant position; e.g.
test[1] = null;
Create a new array with the element removed; e.g.
String[][] temp = new String[test.length - 1][];
Need to get index at string/array to remove: IndexToRemove
for (int i = 0; i < test.length-1; i++) {
if (i<IndexToRemove){
temp[i]=test[i];
}else if (i==IndexToRemove){
temp[i]=test[i+1];
}else {
temp[i]=test[i+1];
}
}
test = temp;
Hope it helpful!

Related

Add array list to a list inside for loop in java

I am trying to add array list to a list inside for loop. in my code, scenario
is array list and it is suppose to be has a new values in every i . for every i i want to save the scenario inside a list list_of_scenarios but i have this error.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
Any idea about how can i fix it?
int[] ActionArrayTest = new int[25];
int[] test27Augest = new int[75];
ArrayList<Hour> scenario = new ArrayList<Hour>();
List<ArrayList<Hour>> list_of_scenarios = new ArrayList<ArrayList<Hour>>();
for (int i = 1; i <= 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
list_of_scenarios.add(i, scenario);
}
On the first iteration of your loop, list_of_scenarios.add(i, scenario); is asking to add scenario to index 1 in your ArrayList. However, at that point, your ArrayList is empty.
Proposed fix:
for (int i = 0; i < 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
list_of_scenarios.add(i, scenario);
}
Note: The documentation states that this method adds the element at that index, but shifts everything else to the right.
If you want to structure your ArrayList such that the element at index 0 was added before the element at index 1, use the plain add() method:
list_of_scenarios.add(scenario);
This method simply adds the element to the 'end' of the list.
Are you trying to create an arraylist of arraylists..Doesnt sound like a good programming approach. If you want to find an element inside that list of lists, it is going to take lot of time. Think about the code complexity to find the last element in the last arraylist. You have to iterate through the list of lists, get each list, iterate through the each list again to find that element.
If all those arraylists have same type, why cant you just add all those elements to the top array list. So you maintain only one arraylist and as you go through the for loop, you add the elements of Scenario to the arraylist.
like this..
List<Hour> list_of_scenarios = new ArrayList<Hour>();
for (int i = 1; i <= 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
//add all the elements of 'scenario' to the list.
list_of_scenarios.addAll(scenario);
}
Good luck..Happy programming.. :)

Remove an element from an ArrayList and move that element into an array java

I'm writing a method that removes an element from an ArrayList of strings, if it is of a given length, and puts the removed String into an Array containing Strings, and I'm a bit confused at how to insert elements into the array after removing them from the List.
My ArrayList is called list, and it's an instance variable in the beginning of my program.
public String[] removeOfLength(String [] arr, int wordLength)
{
arr = new String[list.size()];
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).length == wordLength)
{
list.remove(i);
//arr[i]
}
}
}
I removed the element, but I don't know how to insert it into the array.
The method is supposed to return a String array containing the removed Strings.
Instead of creating an array first, which has to be as long as the list itself, use a list again to hold the removed strings temporarily.
List<String> removedStrings = new ArrayList<String>();
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).length == wordLength)
{
removedStrings.add(list.remove(i));
}
}
Then just convert the list into an array when the method ends
return removedStrings.toArray(new String[removeStrings.size()]);
Just assign the value at a certain index.
Also the remove method returns the value removed from the list.
arr[I]=list.remove(I);
Also you need to return arr at the end of the method. And if the method calling this one expects the array that its providing as an argument to have the elements it won't because you are assigning it a new reference at the beginning.
Also, the array will not fill like a list, there will be gaps if it doesn't remove every element from your list, arrays aren't smart like ArrayLists.
Since array is a fixed length structure and you have to specify the length at the creation, you cannot directly insert removed element to a new array because you don't know how many elements will be there in array.
Instead, you can use the arraylist to keep removed elements temporarily and at the end of the iteration, populate those to a new array (because at that point, you know the length of the array using number of elements in your temporary arraylist).

Generic Array creation and null pointer errors

I have an array of linked list which runs parrallel to an ordered object array. If an extra element is entered into the object array i need to insert an extra element into the same space in the linked list.
I have this method as follows
public static LinkedList<User>[] insertElement (LinkedList<User>[]a, int index, User friend) {
LinkedList<User>[] bp = new LinkedList[nElems];
for (int i=0; i<index; i++){
bp[i]=a[i-1];
}
//index is the position in which i want to insert a new element
bp[index].add(friend);
for (int i=index+1; i<a.length; i++){
bp[i]=a[-1];
}
return bp;
}
When bp is initialised as shown I get a null pointer error
When it is initialised as:
LinkedList<User>[] bp = new LinkedList<User>[nElems];
I get a generic array creation error. What it the correct way to initialise this?
This line:
LinkedList<User>[] bp = new LinkedList[nElems];
..creates an array of null references to LinkedList<User>. You must initialize these before you use them:
LinkedList<User>[] bp = new LinkedList[nElems];
for (int i = 0; i < nElems; i++) {
bp[i] = new LinkedList<User>();
}
You have created an array of linked lists, but you haven't created any LinkedLists within the array.
You need to create the list in each slot of the array before you try and use it.
It seems unlikely that this is what you are actually trying to do though...you seem to be mixing up Arrays and Lists. Really you should use either Collections or Arrays, not mix the two together.
What I guess you are trying to do is having a ordered List of Users. If this is the case you can do this by just having a LinkedList and using
LinkedList<String> users = new LinkedList<>();
users.add( index, friend );
LinkedList.add automatically shifts all elements to the right.

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

How to filter an array in Java?

How can I filter an array in Java?
I have an array of objects, for example cars:
Class:
public class Car{
public int doors;
public Car(int d){
this.doors = d;
}
}
Use:
Car [] cars = new Cars[4];
cars[0] = new Car(3);
cars[1] = new Car(2);
cars[2] = new Car(4);
cars[3] = new Car(6);
Now I want to filter the array of cars, keeping only 4 doors and more:
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
//add cars[i] to a new array
}
}
How should I do this?
Before I did it with a Vector:
Vector subset = new Vector();
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
//add cars[i] to a new array
subset.addElement(cars[i]);
}
}
And then I would make a new array with the size of the Vector. Then I would loop over the vector again and fill the new array. I know this is a very large procedure for something simple.
I'm using J2ME.
EDIT: saw that ArrayList is not in J2ME, but based on documentation, it does have a Vector. If that Vector class is different than J2SE Vector (as this documentation indicates), then perhaps the following code would work:
Vector carList = new Vector();
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
carList.addElement(cars[i]);
}
}
Car[] carArray = new Car[carList.size()];
carList.copyInto(carArray);
The most efficient way to do this--if the predicate you're filtering on is inexpensive and you're accessing it with a single thread--is usually to traverse the list twice:
public Car[] getFourDoors(Car[] all_cars) {
int n = 0;
for (Car c : all_cars) if (c.doorCount()==4) n++;
Car[] cars_4d = new Car[n];
n = 0;
for (Car c : all_cars) if (c.doorCount()==4) cars_4d[n++] = c;
return cars_4d;
}
This traverses the list twice and calls the test twice, but has no extra allocations or copying. The Vector-style methods traverse the list once, but allocates about twice the memory it needs (transiently) and copies every good element about twice. So if you are filtering a tiny fraction of the list (or performance isn't an issue, which very often it isn't), then the Vector method is good. Otherwise, the version above performs better.
If you really need a plain array as the result, I think your way is the way to go: you don't know the number of resulting elements before you filter, and you can't construct a new array without knowing the number of elements.
However, if you don't need thread-safety, consider using ArrayList instead of a Vector. It ought to be somewhat faster. Then use ArrayList's toArray method to get the array.
I can't see much wrong with your code. You could just stick with Vectors throughout though.
You could simplify the second part (where you copy the matching items into the new array) using Vector.copyInto(Object[]).
There's no direct way to remove elements from an array; its size is fixed. Whatever you do, you need to allocate a new array somehow.
If you want to avoid the minor memory overhead of allocating a Vector, another option would be to make two passes over your array. The first time, simply count the number of elements that you want to keep. Then allocate an array that size, and loop over your old array again, copying matching elements into the new array.
You can use System.arrayCopy():
Car[] cars = ...
int length = cars.length < 4 ? cars.length() : 4;
Car filter = new Car[4];
System.arrayCopy(cars, 0, filter, 0, length);
UPDATE: System.arrayCopy is available in Java ME API, unlike Vector.subList(). Thanks for the correction.
You will need to create a new array anyway.
Vector vector = new Vector(array.length);
for (int i = 0; i < array.length; i++) {
if (array[i].doors > 4) {
vector.add(array[i]);
}
}
Car[] result = new Car[vector.size()];
vector.copyInto(result);
This isn't quite efficient, though.

Categories