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()
Related
So, this is part of a method which checks for available rooms within a date range and is meant to return the int [] array of room numbers which are available.
ArrayList roomNums = new ArrayList();
roomNums.toArray();
for (Room room: rooms){
int roomNumber = room.getRoomNumber();
if(room.getRoomType() == roomType && isAvailable(roomNumber, checkin, checkout)){ // This works fine, ignore it
roomNums.add(roomNumber);
}
}
return roomNums.toArray(); // Error here, return meant to be int [] type but it's java.lang.Obeject []
The error occurs at the end at roomNums.toArray()
I saw someone else do this one liner and it worked for them, why is it not for me?
Every element in roomNums is an integer. (I think)
What's the quickest and easiest way to print an integer array containing the available rooms? Do I need to make a loop or can I do something with this .toArray() one liner or something similar to it?
Thanks
Don't use raw types. Replace ArrayList roomNums = new ArrayList(); with
ArrayList<Integer> roomNums = new ArrayList<>();
Then return it as Integer[]
roomNums.toArray(Integer[]::new);
If you need primitive array, then it can be done with stream:
return roomNums.stream().mapToInt(Integer::valueOf).toArray();
See also How to convert an ArrayList containing Integers to primitive int array?
Unfortunately, you will need to use Integer[] if you want to use toArray
List<Integer> roomNums = new ArrayList<>();
// code here
Integer[] arr = new Integer[roomNums.size()];
return roomNums.toArray (arr);
However you can still do it manually like
List<Integer> roomNums = new ArrayList<> ();
// code here
int[] arr = new int[roomNums.size()];
for (int i = 0; i < arr.length; i++)
arr[i] = roomNums.get (i);
return arr;
As mentioned above use the ArrayList to hold your values:
ArrayList<Integer> roomNums = new ArrayList<>();
then you can use the object super class to convert to array
Object[] numbersArray = roomNums.toArray();
then just continue running the for loop and your program
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);
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.
I am getting some weird running times for my mergesort algorithm...I want to run the algorithm (say 1000 times) on the same permuted ArrayList. Right now, I just create an array of ArrayList of size 1000, then time how long it takes to sort each of these, then take the average of the times.
So my question is: am I sorting the same list over and over? If I change one instance of the ArrayList in the array say at index 0, will the other ArrayLists in the array stay the same? I would assume so, but I want to be certain that's not happening? Thanks.
for (int N = 1000; N <= 10000; N += 1000) {
//copy the array
#SuppressWarnings("unchecked")
ArrayList<Integer>[] container = (ArrayList<Integer>[])new ArrayList[N];
ArrayList<Integer> testArray1 = generatePermutedOrder(N);
for(int j=0; j<timesToLoop; j++){
container[j] = testArray1;
}
System.out.print(N + "\t");
// let things stabilize
startTime = System.nanoTime();
while (System.nanoTime() - startTime < 1000000000)
;
// time the routine
startTime = System.nanoTime();
for (int i = 0; i < timesToLoop; i++) {
mergesort(container[i]);
}
If I change one instance of the ArrayList in the array say at index 0, will the other ArrayLists in the array stay the same?
Yes, modifying ArrayList at index 0 won't effect the other indexes. (but make sure that other indexes don't have reference to same ArrayList)
Scenerio 1: (Modifying index 0 will effect index 1)
ArrayList[] arr = new ArrayList[2];
ArrayList aList = new ArrayList();
arr[0] = aList;
arr[1] = aList;
Scenerio 2: (Modifying index 0 will NOT effect index 1)
ArrayList[] arr = new ArrayList[2];
ArrayList aList1 = new ArrayList();
ArrayList aList2 = new ArrayList();
arr[0] = aList1;
arr[1] = aList2;
So, make sure it's Scenerio 2 in your code.
EDIT:
ArrayList<Integer> testArray1 = generatePermutedOrder(N);
for(int j=0; j<timesToLoop; j++)
{
container[j] = testArray1; // same reference pointing to same ArrayList is added in each interation
}
You are adding same reference to each index. So, modifying at any index will effect remaining indexes.
Yes the other ArrayList will stay the same.
For example.
array[0].set(0,object)
Will not affect the ArrayList at array[1]
You said you created an array of ArrayLists, but what did you assign into each slot in that array? Did you create one ArrayList instance and assign it to all 1000 slots in the array, or did you create 1000 different ArrayLists (e.g. using new in a loop) and assign a different one to each array slot?
If you store multiple references to the same object in multiple places, changes to that object will be visible through all the references.
If you just create an array of ArrayList objects they're all null. If you then iterate through the array and instantiate each ArrayList with new, then they're all different (each call to new ArrayList() will create a new one).
It's possible to put the same ArrayList reference in every element of the array by creating an ArrayList and then iterating through the array and assigning every element of the array the value of the (already created) ArrayList. This is probably not what you want to do.
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);
}
}