Delete element from array [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Removing an element from an Array (Java)
Is there a way I can get rid of some elements in an array.
for instance, if i have this array
int testArray[] = {0,2,0,3,0,4,5,6}
Is there a "fast" way to get rid of the elements that equal 0
int resultArray[] = {2,3,4,5,6}
I tried this function but I got lost using Lists
public int[] getRidOfZero(int []s){
List<> result=new ArrayList<>();
for(int i=0; i<s.length; i++){
if(s[i]<0){
int temp = s[i];
result.add(temp);
}
}
return result.toArray(new int[]);
}

Java arrays can't be resized. You need to create a new array.
Count the non-zero elements in the array. Create a new array that size. Copy the elements from the old to the new array, skipping over zero elements.
You can do this with lists. Your best bet is to create a list of Integers; add non-zero elements to it; then use toArray to create an array from the list.

You're quite close, but:
Your generics were messed up (List<> is syntactically invalid)
Your comparison was only adding the element if it was less than zero (rather than adding it if it was not equal to zero)
You were calling the wrong toArray() method.Because ints are primitives, you have to turn the list back into an array yourself.
public int[] getRidOfZero(int[] s) {
List<Integer> result = new ArrayList<Integer> ();
for (int i : s) {
if (i != 0) {
result.add(i);
}
}
int[] toReturn = new int[result.size()];
for (int i=0; i<result.size(); i++) {
toReturn[i] = result.get(i);
}
return toReturn;
}

Since you're starting with an array, you'll need to create a new array and copy the items from the old array, excluding the zeros.
If you remove a bunch of zeros at once, this is going to be fast.
Otherwise, you'll need to begin with the doubly-linked LinkedList.
LinkedList has an iterator that allows you to move along the list and remove elements, which will be a constant-time operation.

Related

Simplest way to add an item to beginning of an array in Java

I need the simplest way to add an item to the front of an Java array.
I need the Java array NOT the ArrayList.
There are two ways to do this. One, using Objects or another using generics. I recommend you to use generics because gives you more flexibility as you gonna see in these examples.
In this first implementation the function add2BeginningOfArray is using generics:
public static <T> T[] add2BeginningOfArray(T[] elements, T element)
{
T[] newArray = Arrays.copyOf(elements, elements.length + 1);
newArray[0] = element;
System.arraycopy(elements, 0, newArray, 1, elements.length);
return newArray;
}
Calling this function is really simple. For instance, if you have a class Dot and you want to add an element to the beginning of an array of Dot objects you just need to do this:
int size = 20;
Dot[] dots = new Dot[size];
for (int i = 0; i < size; i++) {
dots[i] = new Dot("This is a dot");
}
Dot goal = new Dot("This is a goal");
System.out.println(Arrays.toString(add2BeginningOfArray(dots, goal)));
You can also implement a function declaring the function parameters as Object as shown in this example:
public static Object[] add2BeginningOfArray(Object[] elements, Object element){
Object[] tempArr = new Object[elements.length + 1];
tempArr[0] = element;
System.arraycopy(elements, 0, tempArr, 1, elements.length);
}
Now, what is the problem? Well, not a big problem but now you need to declare your array as Object[] and use this kind of declaration to work with it.
Object[] foo = {"2", "3", "4"};
//adding an element to the beginning array
Object[] numbers = add2BeginningOfArray(foo, "1");
System.out.println(Arrays.toString(numbers));
For me the generics approach is cleaner and more scalable, so I really recommend it over the Object approach.
Apache Commons Lang class 'ArrayUtils' makes this very easy, if that is an option for you:
char[] arrayA = {'b', 'c'};
char[] arrayB = ArrayUtils.add(arrayA, 0, 'a');
// arrayB: [a, b, c]
for(int i = roadVehicles.length; i > 0; i--) {
if (roadVehicles[i-1] != null) {
roadVehicles[i] = roadVehicles[i-1];
}
}
roadVehicles[0] = car;
As per the Java tutorials (which I thoroughly recommend beginners to work through)
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Because arrays cannot be resized - you can overwrite the first element, but to perform an insert you must create a new array 1 larger than the previous one, put your new element in the first position and fill the rest of the array with the existing elements.
Of course, in practice don't do this. Instead use a collection that suits your actual use-case.
So the actual answer to your question is: The simplest way to add an item to front of a java array is to use a better collection type such as a Deque.
I cannot think of any valid reason in Java to not use a more appropriate collection than a raw array if inserting to the front is required.
Once created an array cannot be resized. If you have to add an element you'll need to create a new array.
If you know the array type it's trivial, but a nicer solution will work with any array type, using the java.lang.reflect.Array
Example code:
public static Object addElementInFrontOfArray(Object array, Object element) {
int newArraySize = Array.getLength(array)+1;
Object newArray = Array.newInstance(element.getClass(), newArraySize);
//Add first element
Array.set(newArray, 0, element);
for (int i=1 ; i<newArraySize; i++) {
Array.set(newArray, i, Array.get(array, i-1));
}
return newArray;
}
Consider that you can pass a int[] array as parameter but a Integer[] arrary will be returned
Considering this source
https://www.journaldev.com/763/java-array-add-elements
you can add new elements at the beginning of you array by doing this:
public static Object[] add(Object[] arr, Object... elements){
Object[] tempArr = new Object[arr.length+elements.length];
System.arraycopy(arr, 0, tempArr, elements.length, arr.length);
for(int i=0; i < elements.length; i++)
tempArr[i] = elements[i];
return tempArr;
}
Why not just use an ArrayList?
You could use an Array convert it to a List as follows:
List<Integer> myList = Arrays.asList(1,2,3);
//Instead of 1,2,3 you could create an Integer array: Integer[] myArray = {1,2,3};
myList.add(0, 25);
If you decide doing this way, you could check the answers of this question:
Java Arrays how to add elements at the beginning
or just check out the documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
here's a concrete example of the simplest way I could find:
List<StackTraceElement> stack = new ArrayList<StackTraceElement> (Arrays.asList (e.getStackTrace()));
stack.add (0, new StackTraceElement ("class", "method", "file", 25439));
StackTraceElement[] newStack = new StackTraceElement[stack.size()];
newStack = stack.toArray (newStack);
e.setStackTrace (newStack);
Basically it uses java.util.Arrays.asList() to turn the array into a List, adds to the list and then turns the list back into an array with List.toArray().
As everybody has said, you can't really add to the beginning of an array unless you shift all the elements by one first, or as in my solution, you make a new array.
Just .unshift()
This adds an element to the beginning of an array.

Reverse order of the Arrays stored in ArrayList

I'm working with Processing and IGeo library and I have an ArrayList of IVec[] arrays:
ArrayList<IVec []> v = new ArrayList<IVec[]>();
For every I of the ArrayList I have a collection of IVec [] arrays that represent the coordinates of the control points of a curve. I need to reverse the order of the IVec [] control points keeping the same order of the ArrayList (I'm trying to invert curve seam reversing control points order and keeping the original order of the curves) but I can't understand how to do this.
Can anyone help me?
I won't provide you a full solution, but will guide you through it:
Iterate on the array list v
for each item in it (IVec[]),
Convert the array to a collection (for example using Arrays.asList)
Use Collections.reverse to reverse the items in the list
Conver it back to an array
You can use Collections.reverse
You can also use a stack data structure. You can iterate over collection you wish to reverse by pushing the elements into the stack. Then, when you actually want to use the elements, you pop each element from the stack, which will allow you to iterate over the collection in reverse order.
This solution is working:
for (int i=0; i<v.size (); i++) {
IVec [] vert=v.get(i);
for (int j=0; j<vert.length/2; j++) {
IVec temp = vert[j];
vert[j]=vert[vert.length -1 - j];
vert[vert.length - 1 - j] = temp;
}
}
Try this;
Create a Helper method/function that takes and returns array.
Inside the Helper method, use Collections.reverse
return the reversed array.
call this helper method inside a loop as below:
for(int i = 0; i < OutArray.length; I++)
{ // Here get the inner Array and pass it to Helper method.
// Add the return array to newArray List
}
return newArrayList.
This should work (not the most efficient way, but easily understood):
public static <T> void reverseElements(ArrayList<T[]> list) {
ArrayList<T> tempList = new ArrayList<T>();
for(T[] arr : list) {
tempList.clear();
for(T t : arr)
tempList.add(t);
Collections.reverse(tempList);
tempList.toArray(arr);
arr = tempList.toArray(arr);
}
}

Removing duplicates from an array list of characters using a loop? [duplicate]

This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed 7 years ago.
public static ArrayList<Character> removeDuplicates (ArrayList<Character> data) {
ArrayList<Character> newList = new ArrayList<Character>();
for (int i = 0; i < data.size() - 1; i++) {
if (!newList.contains(data.get(i)))
newList.add(0,(data.get(i)));
}
return newList;
}
Here is my code so far. I'm not understanding how this is not working
You can use a Set. A Set is a Collection that doesn't let duplicates of Objects.
I'm not sure what Object type your List is of, but let's say your were using String:
//replace all instances of 'String' with whatever Object type you are using
Set<String> mySet = new HashSet<>();
for(String s : data){
mySet.add(s);
}
Then if you want to send the data to a List, do:
ArrayList newList = new ArrayList(mySet);
There are 2 problems with your implementation.
You're not counting all of the items in the array. You should do either i <= data.size() - 1 or i < data.size(). Right now you're missing the last item.
You're not adding items to the end of the list. Instead, you're repeatedly overwriting the zeroth (first) value. EDIT: Sorry, that was incorrect. You're inserting at the beginning of the list, which will work but is inefficient for the most commonly used lists (e.g. ArrayList).
Here is the fixed version. The problem areas are commented out with /* */.
List<Object> newList = new ArrayList<Object>();
for (int i = 0; i < data.size() /* - 1 */ ; i++) {
if (!newList.contains(data.get(i)))
newList.add( /* 0, */ (data.get(i)));
}
return newList;
EDIT: Using contains(...) on a list is slow. You can optimize and simplify this by using a Set. A set is a collection which has unique values. Adding the same value twice has no effect. We can take it a step further and use a LinkedHashSet as the implementation class, which will maintain the same ordering as was in the original list.
return new ArrayList<Object>(new LinkedHashSet<Object>(data));

Given a String array, how to create a second array which is a rearrangement of the original?

I am trying to create a method to takes an array of names and returns a copy of the list with the names randomly rearranged. The code below returns a new list with duplicated names. what can I do to shuffle names of the new list instead?
public static String[] shuffle(String []names)
{
int num =0;
String [] newArray = new String [names.length];
Random r = new Random ();
for(int i = 0; i<names.length; i++){
num = r.nextInt(names.length);
if((i-1)!=num){
newArray[i]=names[num];
}
}
return newArray;
}
You can use Collections.shuffle() to shuffle a list.
If you are eager to do it by your own - have a look on fisher-yates shuffle.
(Pseudo code:)
for (i = n-1; i >= 0; i--)
swap(names,i,r.nextInt(i+1));
(Where swap() is a standard swapping function to swap two elements in an array)
(Note, if you want a new instance with the shuffled array - just copy it using Arrays.copyOf() before running the algorithm.
Like others have suggested there are already other cleaver/easy ways to do this, but to solve the issue in your code you need to make the newArray a copy of the names array (you can can use Arrays.copyOf) and then properly swap the values, like:
if(i!=num){
String aux=newArray[i];
newArray[i]=newArray[num];
newArray[num]=aux;
}
Collections.shuffle(list)
Info
You can use the ToList to make it a list for the shuffle and then back to an array with ToArray.
This may not be the most efficient but it is the easiest.
public String[] shuffle(String[] ss) {
List<String> list = Collections.shuffle(Arrays.asList(ss));
return list.toArray(new String[ss.length]);
}

How can I dynamically add items to a Java array?

In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}

Categories

Resources