arrays in android programming - java

I am new in android programming.
Here is my question
I tried to declare an array before onCreate() method like
int[] userselected;
Note that i want to use this array to store ids of buttons user had pressed.
Then i tried to find no. of elements in this array with
int noOfElements = userselected.length;
which game me an error.
Then I changed declaration to
int[] userselected = {};
it worked, but when i tried to put an id in this array with code
userselected[1] = R.id.textview1;
it again gave me an error.
I also tried declaring array as
int[] userselected = new int[4];
but then, when i tried to find how many elements have already been stored,
userselected.length
always gave number 4.
Please tell me, how can i get what i want

You need to use ArrayList. It will give you a more flexible structure giving your case.
ArrayList<Integer> userselected = new ArrayList<Integer>();
userselected.add(R.id.textview1); //To add id.
int noOfElement = userselected.size(); //to get size

an array is fixed size. so when you declare this array
int[] userselected = new int[4]
you are creating an array with a fixed size of 4. The array index is zero based so its from [0] to [3]. I recommend you use an ArrayList object like the top answer states
when you do this:
int[] userselected = {};
it is the same as this:
int[] userselected = new int[0]; // empty
and you got an error from this:
int[] userselected;
because you have not allocated any space in memory

Java primitive arrays, such as int[], are constant in length and cannot contain more than their initial length. If you need an array that can change in size, you need to use fx. a List implementation. I would suggest you read up on basic Java before you start developing Android, it would save you a lot of time in the long run.

I think this page can help: http://www.javaclass.info/classes/java-array/array-examples-demonstration-and-code-snippets.php
In the array declaration you do, you say that its size is 4 elements, therefore the length method will always return 4.
regards

declare it as a integer array then Add this to your code
Integer a=0;
for (int i=0;i>userselected.length;i++)
{
if(userselected[i]!=null)
{
a++;
}
}
then a will give you the count you need:) cheers:)

Related

How do I add arrays to an Arraylist of Arrays (Arraylist<Integer[]>)

I want to save the steps pf my player-character in a Sokoban-game.
So at first i want to fill an Array of int x and y, called "pos" with the actual position of the character.
And than i want to add this array to an ArrayList of Arrays, called "moves".
Array for one player-position:
int[] pos = new int [2];
ArrayList for all steps, the player made in the level:
Arraylist<Integer[]> moves = new ArrayList<>();
"int[]" makes an error, if placed inside the pointy brackets at the ArrayList.
How do i add the Array pos to the ArrayList moves?
This works completely fine with int[]. However int[] != Integer[], Use same in both places.
int[] pos = new int[2];
ArrayList<int[]> arrayList = new ArrayList<>();
pos[0] = 1;
pos[1] = 2;
arrayList.add(pos);
System.out.println(arrayList.get(0)[0]+ " "+ arrayList.get(0)[1]);
int and Integer are two different things (I struggled with this as well when I first learned Java a long time ago.
int is a so-called primitive datatype, which means it is not an object. Integer is a wrapper class, basically a class whose only purpose is to contain an
int so that it can be handled as an object. Since Java 5, there is "autoboxing", which means you can assign int values to Integer variables and vice versa, and the compiler will handle it silently. This tends to muddle the difference, but it still is there and important - such as in this case.
So if you want to store instances of int[] in an ArrayList, you need an ArrayList<int[]>, not an ArrayList<Integer[]>.
However, it is impossible to have an ArrayList<int> because ArrayList can only store Objects (the generic types exist only for the compiler), not primitives.
Oh yes, and to add an element to the list, use
Arraylist<int[]> moves = new ArrayList<>();
arrayList.add(pos);
You could have found this in the API doc for ArrayList - you should really learn to use the API doc, you will need it all the time to answer questions such as this.
You can also make class (for example Pos) and make x and y as attributes and make constructor. The you can make the type of arraylist is Pos
ArrayList arrayList = new ArrayList<>();
arrayList.add(new Pos(3,2));

Changing the number of dimensions an Java array has

Is there a way of changing the number of dimensions an array has, i.e making this
int[][] i = new int[3][3];
but using it like this
getArray(i); //where getArray only accepts one dimensional arrays
?
You cannot change the number of dimensions in a Java array or array type.
But you can make use of the fact that a Java array is an object ... and subtyping .. and declare a getArray method like this:
Object getArray(Object[], ...) { .... }
You can call this method on a int[][] instance, but a runtime typecast is needed to cast the result to an int[].
For example:
Object getArray(Object[] array, int i) { return array[i]; }
int[][] big = new int[3][3];
int[] slice = (int[]) getArray(big, 0);
On the other hand, if you are really asking about how to flatten a multi-dimensional array into a 1-D array, the getArray method needs to allocate a new array, fill it from the original and return it.
Note you would be returning a brand new array that is unconnected to the original one. And copying an N x N .... x N array is expensive.
For more details: Flatten nested arrays in java
Java is statically-typed language. This means that you cannot change a variable's type at runtime. But in this particular case you can simply use the following invocation:
getArray(i[2]); // put anything between 0 and (outerArrayLength-1) instead of 2 here

How to add values to Double[] arraylist [duplicate]

This question already has answers here:
I'm getting an error in my Java code but I can't see whats wrong with it. Help?
(5 answers)
Closed 5 years ago.
I created this arrayList:
Double[] arrayOfNumbers = new Double[List.size()];
And I try to add it numbers with this:
arrayOfNumbers.add(0.9);
This gives me an error message that says:
Cannot invoke add(double) on the array type Double[]
So, how can I add that value in this Double[] arraylist?
That is not an ArrayList. That is an array.
You can declare an arraylist of doubles as :
int initialCapacity = 20;
List<Double> doubles = new ArrayList<Double>(initialCapacity);
doubles.add(0.9);
You can add more than 20 values in an ArrayList even though the initial capacity is specified as 20.
But to declare an array and populate it:
double[] doublesArray = new doubles[20];
doubles[0] = 0.9;
doubles[1] = 0.5;
.....
doubles[19] = 0.7; // 19 is the last index for an array of size 20.
If you add more than 20 here, you will get ArrayIndexOutOfBoundsException
Double[] is not ArrayList to add to an array you can use :
Double[] arrayOfNumbers = new Double[List.size()];
arrayOfNumbers[0] = 0.9;
Instead to add to an ArrayList you can use :
List<Double> arrayOfNumbers = new ArrayList<>();
arrayOfNumbers.add(0.9);
Arrays and lists are different things. Arrays don't have an add method, but are assignable by the subscript ([]) operator:
arrayOfNumbers[0] = 0.9;
Double[] arrayOfNumbers = new Double[List.size()] is not a List
it is an array.
We declare arrays with [] and lists with <> and generics.
For example `
int[]arr=new int[3] is an array of 3 ints, but List<Integer>list=new ArrayList<>() is a list of integers(not primitive ints you CANNOTwrite code like this List<int>=new ArrayList<>()
Hope that helps!
java.util.List is a different that an array(which has limited predefined size).
you can't declare/perform as above you did in question, java compiler will complain if you do so.
you are phasing a error like,
Cannot invoke add(double) on the array type Double[]
because an array(arrayOfNumbers) do not having a such method(add) which you can execute on arrayOfNumbers.
However,
general syntax to initialize of an array of any type(here in example, Integer taken FYI) is likewise,
int intArray[] = {1,2,3}; // initialize at the time of creation
or
int arrayOfNumbers [] = new int[] {1, 2, 3};
or
intArray[index] = 1;
Moreover, you can switch from array to List & vice-versa as likewise,
List<Integer> list = java.util.Arrays.asList(arrayOfNumbers);
or
Integer [] intArray = list.toArray(new Integer[list.size()]);
A List is an Interface that extends another interface called Collection, so a List is-a Collection. An Interface defines and describes behavior, it defines a contract that another class must conform to, and one of the classes that does so is called java.util.ArrayList, and add() is one behaviour defined in the List contract, because a List must have the ability for things to be added to it. An ArrayList is one type of a List. What you have created is NOT an ArrayList, it is an Array.
An array is a primitive data structure, once created, it's size cannot be changed, If you wish to add a new element to an array you have to create a new array that is bigger, then transfer all elements from the old array to the new one. Under the covers an ArrayList does exactly that. THIS IS HOW YOU CREATE an ArrayList :
//a list of Objects of type `Double`
List<Double> listOfNumbers = new ArrayList<>();
if you wish to add an element to this list, you would do this :
listOfNumbers.add(5.2);
You do seem like you still need to read a beginners book and practice basic Java programming. I would like to suggest this playlist
This will really be helpful to you, and remember you can only learn something by doing it hands-on, NOT by just watching somebody else doing it.

Store an array within a 2d array Java

So why doesn't this work? Not really sure why this isn't possible- I just want to store an array of size 2 inside a 2d array.
I know this would be equivalent to setting storage[0][0] = array[0] and storage[0][1] = array[1], but just wondering why this is incorrect.
public class Test {
public static void main(String[] args) {
boolean[][] storage = new boolean[10][2];
boolean[] array = new boolean[2];
array[0] = true;
array[1] = false;
storage[0][] = array; //Why can't I do this?
}
}
Thanks in advance
You have a stray pair of brackets in your assignment. Just use
storage[0] = array;
First of all boolean[][] storage = new boolean[10][2] declares an array and initialise it.
So, you have created 11 arrays. One of boolean[] element type and 10 of boolean type.
It's good, If you want to access it's members directly, but if you create an inner array lately with new boolean[], it's an overhead.
Use boolean[][] storage = new boolean[10][]; instead.
Then, you can access it's elements, which are boolean[] type, and assign your array to it.
storage[0] = array;
Your problem is the stray square brackets(as I'm sure you know). Your code should look like this:
storage[0] = array;
The previous answers did not really explain why though, so that's what I'll do.
What your trying to do is make the first position(storage[0]) hold the same value as array. array is 1 dimensional, so it can only be part of storage, which is 2 dimensional.

Making A Copy of an Array List without it looping

I have an array which is uses inheritance i think basically there is an array which holds Food and Drink and looks something like this
allFoodAndDrink.add(new Food(parameters);
allFoodAndDrink.add(new Drink(parameters);
so both type food and drink are stored in the snack array called allFoodAndDrink but when wanting to make a copy of the array from certain start index to the a end index i got told to use:
Arrays.copyOfRange();
but when using it like this:
int[] drink = Arrays.copyOfRange(allFoodAndDrink, 5, 10);
it spits out and error and its suggestion is to convert it to Arrays.copyOf() when switching to that it then spits out another error to revert back to Previous
any ideas
Make a use of ArrayList#subList() and ArrayList#toArray():
int first = ...;
int last = ...;
Foods[] drink = new Foods[last - first];
allFoodAndDrink.subList(first, last).toArray(drink); // fill the array
Assuming you mean ArrayList and not array you can copy a List using
allFoodAndDrink.subList(5,10);
Please note that this would be a 'shallow copy' and references would point to the same objects
You can use ArrayList's method sublist(int fromIndex, int toIndex).
ArrayList<Foods>() list = allFoodAndDrink.subList(0, allFoodAndDrink.size()-1);
Foods[] array = (Foods[]) list.toArray();
http://docs.oracle.com/javase/6/docs/api/java/util/AbstractList.html#subList(int, int)
You can convert an ArrayList to an array with toArray()-method: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#toArray()
Thanks for the response I was just following and example that's where the int came from I'll try a few and get back to you

Categories