I have a listview.
private String[] listView2 = {"aa","aa","aa"};
int a = 0;
Int values will decide to add the number of content
So if a==2.
listView2 = {"aa","aa"};
if a==5
listView2 = {"aa","aa","aa","aa","aa"};
You're clearly familiar with array initializers where you specify the content up-front... but you can also create arrays just by specifying the length, like this:
String[] array = new String[length];
This will create an array where every element is a null reference (or the a 0, false or '\0' for numeric, Boolean or character arrays respectively). You then just need to populate it. You could do that with a loop:
String[] array = new String[length];
for (int i = 0; i < length; i++) {
array[i] = "aa";
}
Or you could use the Arrays.fill method:
String[] array = new String[length];
Arrays.fill(array, "aa");
One comment on your title though - it's worth understanding that once you've created an array, you can't actually add elements to it (or remove elements from it). The array object has a fixed size. If you do:
String[] array = new String[4];
...
array = new String[5];
then that doesn't add an element to the array - it creates a new array of length 5, and assigns a to that array to the variable array. Any other variables which still have a reference to the original array won't see any change.
If I understand you correctly this is what you want:
private String[] listView2 = new String[a];
for(int i = 0 ; i<a ; i++){
listView2[i] = "aa";
}
An array has a set number of things it can contain.
If you want to have a dynamic list that can change size, then you should probably use ArrayList<String> like this:
List<String> list = new ArrayList<String>();
for(int i = 0; i < a; i++)
{
list.add("aa");
}
Unlike arrays in other languages, eg javascript, java arrays are fixed length.
If you want to add another element to a full array, you must create another larger array, copy the elements over and assign the end element.
Don't use arrays! They are a pain. Instead use a List, which will expand in size automatically when needed.
Related
i am dynamically adding items to array-list after i wanted to
Initialize Variables using this array-list items
my array-list is
ArrayList<String> dayCountList = new ArrayList<String>();
i try to do like this but it doesn't work
for (int i = 0; i < dayCountList.size() ;i++) {
double day+"i" = Double.parseDouble(dayCountList.get(i));
}
You can create a array or array list of double type like this.
ArrayList<String> dayCountList = new ArrayList<String>();
.
.
double day[]=new double[dayCountList.size()];
// now use your loop like this
for (int i = 0; i < dayCountList.size() ; i++) {
day[i] = Double.parseDouble(dayCountList.get(i));
}
Now you can call your variables like day[0], for first element
day[1] ,for second and so on.
Hope this helped you.
If you are doing this, then you probably did not understand the purpose of array lists is. One purpose of array list is exactly to avoid creating a whole bunch of variables named day1, day2, day3 and so on.
You seem like you want to transform every element in the array list to a doubles. Why not create another ArrayList<Double> or double[] to store the transformed elements? Instead of writing day1, day2, you can say days.get(0), days.get(1) in the case of array lists. With arrays, you can do days[0], days[1] and so on.
ArrayList<Double> days = dayCountList.stream()
.mapToDouble(Double::parseDouble)
.boxed()
.collect(Collectors.toList());
// or
double[] days = dayCountList.stream()
.mapToDouble(Double::parseDouble).toArray()
I am looking for a solution how I can get an array of contains from another one.
For example:
I have an array:
Array= [S1!!T1, S1!!T2, S1!!T3, S2!!T1, S2!!T2, S3!!T1, S3!!T2, S3!!T3]
I am looking for elements in "Array" that contain "S2" and write them to another one. so i should get:
Result = [S2!!T1, S2!!T2]
I already tried the Arrays.asList(I).contains(i) but this is not what i am lookig for i think.
If you wish to copy elements of one array to another, first thing you need to do is loop through the elements of one array and if you find a match then store it into another array.
Let's say you have the following array:
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
We don't know how many of those elements in the array are going to match until we loop through them so we have two choice:
Create another array with the same size as arr (cause some null values in array if not all entries of arr re matched)
Use ArrayList and then later convert ArrayList to array if needed
See below:
public static void main(String[] args) {
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
List<String> s2List = new ArrayList<String>();
//loop through arr and for each element check if it contains S2
for(int i = 0; i < arr.length; i++) {
//if it contains S2 then it returns true and we add it to list
if(arr[i].contains("S2")) {
//add to list the element
s2List.add(arr[i]);
}
}
//print the list for testing
System.out.println(s2List);
//if you wish to store the elements to array then
//now we know how many matched, so we can create array with the
//size of elements in s2List
String[] sArr = new String[s2List.size()];
//Here loop through the list and assign values to array
for(int i = 0; i < s2List.size() ; i++) {
sArr[i] = s2List.get(i);
}
//print the array
System.out.println(Arrays.toString(sArr));
}
You can also use other methods that convert a List to array directly but, above should give you an idea of how to resolve the question you asked.
You could use Java 8 streams
String[] filtered = Stream.of(strings).filter(s -> s.contains("S2")).toArray(String[]::new);
How do I initialize the values of an ArrayList?
I found this on the internet, but it doesn't work.
ArrayList<Kaart>[] hand = (ArrayList<Kaart>[]) new ArrayList[AANTALSPELERS];
All elements of hand are null. I get a nullPointerException because of that. Kaart is a class I created. AANTALSPELERS is a private static final int.
An array of Objects has elements initialized to null (just like how an array of ints is initialized to zeros).
So before you can use the elements of the array, you have to initialize each element.
ArrayList[] al = new ArrayList[5];
for( int i = 0; i < al.length; i++ )
al[i] = new ArrayList();
This is the correct way, using generics. Notice that the warning is unavoidable (you can use a #SuppressWarnings annotation if that's a problem):
ArrayList<Kaart>[] array = (ArrayList<Kaart>[]) new ArrayList[AANTALSPELERS];
for (int i = 0; i < AANTALSPELERS; i++)
array[i] = new ArrayList<Kaart>();
Consider using Guava's ListMultimap where the key is the index.
ListMultimap<Integer, Kaart>
It will take care of all the list initialization for you.
you created a Array of AANTALSPELERS elements and each element can hold an ArrayList.
Since you have not added any ArrayList to the Array, the Array will have the default element null.
You also need to do something like this to populate the Array with ArrayList
for(int i = 0; i < hand.length; i++)
hand[i] = new ArrayList();// or the arraylist you have
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);
}
}
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!