How to remove all elements in String array in java? [duplicate] - java

This question already has answers here:
Empty an array in Java / processing
(8 answers)
Closed 2 years ago.
I would like to remove all the elements in the String array for instance:
String example[]={"Apple","Orange","Mango","Grape","Cherry"};
Is there any simple to do it,any snippet on it will be helpful.Thanks

If example is not final then a simple reassignment would work:
example = new String[example.length];
This assumes you need the array to remain the same size. If that's not necessary then create an empty array:
example = new String[0];
If it is final then you could null out all the elements:
Arrays.fill( example, null );
See: void Arrays#fill(Object[], Object)
Consider using an ArrayList or similar collection

example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

Reassign again. Like example = new String[(size)]

list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.

Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.

Just Re-Initialize the array
example = new String[size]
or If it is inside a running loop,Just Re-declare it again,
**for(int i=1;i<=100;i++)
{
String example = new String[size]
//Your code goes here``
}**

Related

how to make objects immutable in java [duplicate]

This question already has answers here:
Immutable array in Java
(15 answers)
Closed 8 years ago.
I have following piece of code :
final int[] a = new int[5];
a[0] = 10;
a[0] = 5;
this code is perfectly fine as I am modifying the object and not the reference but now I want something like this :
int[] a = final new int[5];
so line 3 above will fire an error that I am trying to change immutable array. Is there any simple way to do it? There is a function in collections but I don't want to use any type of collection.
Is there any simple way to do it?
With a plain array, no. Arrays will always be mutable, so if you want this functionality you'll have to wrap an array and provide a mechanism for reading it (and not one for writing to it). There are already utilities in the standard JDK classes that can do this for you, like in Collections as you state.
You can, for example, use an unmodifiable list as returned by Collections.unmodifiableList instead. For example, to create an unmodifiable list containing 1, 2 and 3:
List<Integer> a = Collections.unmodifiableList(Arrays.asList(1, 2, 3));
Without some sort of wrapper (be it standard or not), what you're asking for can't be done.
If you declare:
final int[] myarray = new int[5];
it will not make your array immutable as you expect. The reference myarray will be final, but contents of this array can be changed.
As you do not want to use Collections Framework, make your own wrapper class over your array, to prevent modifying it's contents. And it will make your array immutable.

continuously changing array size [duplicate]

This question already has an answer here:
How to manage Continuous Changing values in an array of strings [closed]
(1 answer)
Closed 9 years ago.
I have an array of strings but the values in array is changing continuously.
Is there any other way of managing the array except removing items and changing index locations?
public String[] deviceId=null;
deviceId=new String[deviceCount];
in my case deviceCount is changes as new device comes.
so i continuously need to change array size and add or remove items
Use ArrayList in place of String[] ..
And you can also easily cast ArrayList to String[] for your final output as
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
You could use a List. It changes size depending on how many objects you put in it.
List<String> list = new ArrayList<String>;
public static void main(String[] args) {
list.add("string 1"); //Add strings to the list
list.add("string 2");
System.out.println(list.get(0)); //Get the values from the list
System.out.println(list.get(1));
}
Instead of using Arrays, you could use ArrayLists. You can add as much as you want to them without having to re-size the array and once you no longer need an item it can be removed. Here is a link to an overview of ArrayLists and some examples using them: http://www.tutorialspoint.com/java/java_arraylist_class.htm
Hope this helps.
If you know the max count of devices. Then you can define an array with max size.
String[] deviceId = new String[MAX_DEVICE_COUNT];
Or else simply go with a List.
List<String> deviceId=new ArrayList<String>();
Don't worry about performance, so much with a array.
- In Java arrays are initialized at the time of its creation whether its declared at class level or at local level.
- Once the size is defined of an array in Java it can't be changed.
- Its better to use Collection like List.
- It has the flexibility to add and delete the items in it, and one can also at items at desired location in the List.
- List is an Interface in Java, you can use its concrete sub classes like ArrayList, LinkedList..etc.
Not sure whether i got the question correctly but you can use ArrayList or LinkedList if the size is going to change dynamically.

How can I remove duplicates out of an ArrayList? [duplicate]

This question already has answers here:
Java - Removing duplicates in an ArrayList
(19 answers)
Closed 7 years ago.
for (int i = 0; i < arrayP.size(); i++) {
if (arrayP.get(i) == What to put here?) {
arrayP.remove(i)
}
}
If I put i+1 it just compares side by side. How can I get it to run through each element?
Element 1 then run through the whole ArrayList. Then element 2 run through ArrayList.
You can use a LinkedHashSet:
list = new ArrayList<>(new LinkedHashSet<>(list));
If the order of elements does not matter, you should use a normal HashSet instead. In fact, if it's logical to do so, you might consider using a Set instead of a List in the first place. Read about the differences between the two and pick the structure that's more appropriate.
try this
Set arrayPSet = new LinkedHashSet(arrayP);
now arrayPSet holds your array removing it's duplicate values, then you can use it, you can
re-assign your list to this set once again, like
arrayP = new ArrayList(arrayPSet);
now duplicates are removes
just make sure to override the equals() and hashCode() methods if arrayP list holds objects created by you
ok, i updated it maybe this works, i didnt try the order issue, but there are TreeSet/Comparators/Comparables solutions , just try this modification first

Adding element to next free space in array

I have an array
String[] path={abc,bcd};
I pass this array in a method:
addElement(path);
In method
void addElement(String[] path)
{
// here i got value suppose "qsd" and i want to add it after "bcd" ie 2 index of array
path[path.lenght]="qsd";
}
But this is giving me an error.
I dont want to use an ArrayList.
The biggest problem is that arrays in Java are not trivially resizable. What you wind up doing instead is actually creating a new array, and adding each of the elements to that. This will be slower than the ArrayList code, and uglier as well.
This also means that any code which points to the old array will no longer work. If you only have one instance, you could have addElement return the new array like so
String[] addElement(String old[]){
String arr[] = new String[old.length+1];
//copy all the elements in old...
arr[old.length] = "whatever";
return arr;
}
Then use
path = addElement(path);
You should use ArrayList
Otherwise you have to resize the array by allocating new memory of the size of the original array +1, copy the elements from the old one to the new one, and add in the new element.
You can't change the size of emulated array in GWT (even if javascript arrays support this stuff). You'll have always to create a new instance of array. Most common way to solve this problem is to use one of the collection classes (like java.util.ArrayList) . Example:
ArrayList<String> path = new ArrayList<String>(Arrays.asList("abc","bbc"));
path.add("qsd");

ArrayList initialization equivalent to array initialization [duplicate]

This question already has answers here:
Create ArrayList from array
(42 answers)
Initialization of an ArrayList in one line
(34 answers)
Closed 6 years ago.
I am aware that you can initialize an array during instantiation as follows:
String[] names = new String[] {"Ryan", "Julie", "Bob"};
Is there a way to do the same thing with an ArrayList? Or must I add the contents individually with array.add()?
Arrays.asList can help here:
new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
Yes.
new ArrayList<String>(){{
add("A");
add("B");
}}
What this is actually doing is creating a class derived from ArrayList<String> (the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.
I understand that Java 7 will provide additional language constructs to do precisely what you want.
EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)
Here is the closest you can get:
ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));
You can go even simpler with:
List<String> list = Arrays.asList("Ryan", "Julie", "Bob")
Looking at the source for Arrays.asList, it constructs an ArrayList, but by default is cast to List. So you could do this (but not reliably for new JDKs):
ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")
Arrays.asList("Ryan", "Julie", "Bob");
Well, in Java there's no literal syntax for lists, so you have to do .add().
If you have a lot of elements, it's a bit verbose, but you could either:
use Groovy or something like that
use Arrays.asList(array)
2 would look something like:
String[] elements = new String[] {"Ryan", "Julie", "Bob"};
List list = new ArrayList(Arrays.asList(elements));
This results in some unnecessary object creation though.
The selected answer is: ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
However, its important to understand the selected answer internally copies the elements several times before creating the final array, and that there is a way to reduce some of that redundancy.
Lets start by understanding what is going on:
First, the elements are copied into the Arrays.ArrayList<T> created by the static factory Arrays.asList(T...).
This does not the produce the same class as java.lang.ArrayListdespite having the same simple class name. It does not implement methods like remove(int) despite having a List interface. If you call those methods it will throw an UnspportedMethodException. But if all you need is a fixed-sized list, you can stop here.
Next the Arrays.ArrayList<T> constructed in #1 gets passed to the constructor ArrayList<>(Collection<T>) where the collection.toArray() method is called to clone it.
public ArrayList(Collection<? extends E> collection) {
......
Object[] a = collection.toArray();
}
Next the constructor decides whether to adopt the cloned array, or copy it again to remove the subclass type. Since Arrays.asList(T...) internally uses an array of type T, the very same one we passed as the parameter, the constructor always rejects using the clone unless T is a pure Object. (E.g. String, Integer, etc all get copied again, because they extend Object).
if (a.getClass() != Object[].class) {
//Arrays.asList(T...) is always true here
//when T subclasses object
Object[] newArray = new Object[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
a = newArray;
}
array = a;
size = a.length;
Thus, our data was copied 3x just to explicitly initialize the ArrayList. We could get it down to 2x if we force Arrays.AsList(T...) to construct an Object[] array, so that ArrayList can later adopt it, which can be done as follows:
(List<Integer>)(List<?>) new ArrayList<>(Arrays.asList((Object) 1, 2 ,3, 4, 5));
Or maybe just adding the elements after creation might still be the most efficient.
How about this one.
ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");
This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-
List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();
It's a very cool library that saves you a tonne of time.

Categories

Resources